How to handle varchar columns using Entity Framework?

I have a table with a varchar column, and I'm using the Entity Framework to use this column in the WHERE .

Entity Framework generates a query using N'' , so the index in the column cannot be used. Is there a way to get the Entity Framework to generate a varchar request instead of nvarchar one?

+7
source share
2 answers

In fact, it depends on how you built your EF model, if you use your constructor, you can specify the required data type for each column (in your case, just install varchar and you're done).

If you use a code-based approach, you should decorate the property that this column represents with the corresponding attribute ( string objects in .NET are always Unicode, so it will display nvarchar by default), just do it (with data annotations, if you use StringAttribute , then split it with the IsUnicode property to false ):

 [Column(TypeName = "varchar")] public string YourColumnName { get; set; } 
+6
source

You can use the EntityFunctions.AsNonUnicode (string) method, so EF will not pass the string value as nvarchar. I had the same issue with EF 5 and EDMX, where the Oracle database ignored the varchar2 column index and this worked for me.

 var q = (from TableClass t in TableName where t.varchar2Column == EntityFunctions.AsNonUnicode(someText)); 

MSDN link: https://msdn.microsoft.com/pt-br/library/system.data.objects.entityfunctions(v=vs.110).aspx

+5
source

All Articles