问题
I am trying to run this LINQ expression through Entity Framework Core 3.1.1.
using (Text3Context text3Context = new Text3Context(_constringText3))
{
var aus = text3Context.Ausschreibungen.Where(a => a.InhaltKurzText.Contains(value)).Select(c => c.InhaltKurzText).ToList();
}
Unfortunately it throws the exception: "The data types text and varchar are incompatible in the equal to operator" however, when I run the same expression in LINQPad 6:
string value = "test";
var aus = Ausschreibungen.Where(a => a.InhaltKurzText.Contains(value)).Select(c => c.InhaltKurzText);
aus.Dump();
it works perfectly with no errors.
The sql-querys are slightly different as you can see:
Linq/EF Core:
SELECT [a].[InhaltKurzText]
FROM [dbo].[Ausschreibungen] AS [a]
WHERE (@__value_0 = '''') OR (CHARINDEX(@__value_0, [a].[InhaltKurzText]) > 0)',N'@__value_0 text',@__value_0='test'
LINQPad:
SELECT [a].[InhaltKurzText]
FROM [Ausschreibungen] AS [a]
WHERE ((@__value_0 = N'''') AND @__value_0 IS NOT NULL) OR (CHARINDEX(@__value_0, [a].[InhaltKurzText]) > 0)',N'@__value_0 nvarchar(16)',@__value_0=N'test'
How can I handle this query just as LINQPad does?
The sql-datatype of "InhaltKurzText" is "text", thats the reason of the exception, however, since changing the sql-datatype is unfortunately not an option, and the workarounds are "expensive" I would like to be able to run it in the same way as LINQPad does.
The version of the dependency Microsoft.Data.Sql.Client is 1.0.19.269.1.
Thanks in advance
回答1:
This seems to be caused by some change in EF Core 3.x infrastructure and/or SqlServer provider. LINQPad is irrelevant because it simply delegates the LINQ query to the underlying framework (apparently EF Core 2.x in your case).
According to SqlServer documentation, text
data type is obsolete and represents
Variable-length non-Unicode data in the code page of the server and with a maximum string length of 2^31-1 (2,147,483,647).
So even though the database type is text
, you can map it in EF Core as varchar(2^31-1)
modelBuilder.Entity<Ausschreibungen>().Property(e => e.InhaltKurzText)
.IsUnicode(false)
.HasMaxLength((1 << 31) - 1);
Interestingly, the generated SQL is exactly the same (according to the EF Core log) as the one generated from
modelBuilder.Entity<Ausschreibungen>().Property(e => e.InhaltKurzText)
.HasColumnType("text");
but runs successfully, while the later generates the runtime exception in question.
来源:https://stackoverflow.com/questions/60040654/ef-core-3-1-1-avoiding-the-exception-the-data-types-text-and-varchar-are-incomp