'Entity Framework 6.0 NVarchar vs Varchar
I have a site running in Azure that is causing me headaches. I see a select query as being an expensive query in Azure that is coming from EF.
The query is a select against a varchar
column in the database, but from EF, it is turning it into nvarchar(4000)
, causing the query to time out.
Here is how I'm calling the query in the code:
var myObject = db.MyTable.FirstOrDefault(cm => cm.MyField == entryModel.MyField.Trim());
I have searched through many resources explaining how EF uses nvarchar
instead of varchar
, so I've tried adding this annotation to the field in my model class:
[Column(TypeName = "varchar(50)")]
When that didn't work, I tried adding this to the OnModelCreating
method:
modelBuilder.Entity<MyTable>().Property(x => x.MyField).IsUnicode(false);
I've also tried this to force all strings to varchar
:
modelBuilder.Properies<string>().Configure(x => x.HasColumnType("varchar(1000)"));
The query is still causing performance issues that, according to the activity monitor in the database, the query is still showing as this:
(@p__linq__0 nvarchar(4000))SELECT TOP (1)
blah blah fields
FROM [dbo].[MyTable] AS [Extent1]
WHERE ([Extent1].[MyField] = (LTRIM(RTRIM(@p__linq__0)))) OR (([Extent1].[MyField] IS NULL) AND (LTRIM(RTRIM(@p__linq__0)) IS NULL))
Any ideas as to what is causing this? I'm at a point right now that I'm about to just write a stored procedure to call instead of using this EF query.
EDIT Thanks to @Robert Harvey and @StriplingWarrior for their help. Removing the inline trim allowed EF to recognize the varchar change as well as removing the TRIM from the actual SQL calls.
var myField = entryModel.MyField.Trim();
var myObject = db.MyTable.FirstOrDefault(cm => cm.MyField == myField);
Thanks!
Aaron
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|