Home > Blockchain >  LINQ to Entities does not recognize the method 'System.String Truncate
LINQ to Entities does not recognize the method 'System.String Truncate

Time:10-16

Is there a way for EF Core 3.1 on SQL Server to truncate a string?

I know there is a way for dates and numbers by using DbFunctions.TruncateTime and DbFunctions.Truncate.

For example I have a select expression where I want to truncate the address string:

context.Items.Select(x => new ItemModel
    Zipcode = x.Address.Zipcode.Truncate(6)
);

This will throw an error:

LINQ to Entities does not recognize the method 'System.String Truncate(System.String, Int32)' method, and this method cannot be translated into a store expression.

CodePudding user response:

LINQ to Entities requires the whole LINQ query expression to be translated to an SQL query. The Truncate function cannot be translated by EF, that is why you get that error.

You can try DbFunctions.Left which returns a given number of the leftmost characters in a string.

context.Items.Select(x => new ItemModel
    Zipcode = DbFunctions.Left(x.Address.Zipcode, 6)
);
  • Related