Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Linq to Entities Datetime

I have the following code

var dates = query.Select(
                 x => DateTime.ParseExact(x.Date, "yyyy-MM", CultureInfo.InvariantCulture));

var minDate = dates.Min(x => x);

But When I execute that, I get the exception

System.Data.Entity.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' method, and this method cannot be translated into a store expression.

What am I doing wrong? And how I can fix that?

like image 211
Jim Blum Avatar asked Dec 07 '25 17:12

Jim Blum


1 Answers

Well, the error is actually quite clear. There is no translation in Linq to Entities of ParseExact to SQL.

Remember, Entity Framework, under the covers, converts the query to a SQL command or set of commands. If EF doesn't know how to translate something, it throws this error.

One possible solution, while not terribly efficient, is to convert the IQueryable to IEnumerable, which will allow you to execute the statement.

var dates = query.ToList().Select(
             x => DateTime.ParseExact(x.Date, "yyyy-MM", CultureInfo.InvariantCulture));
like image 78
Erik Funkenbusch Avatar answered Dec 09 '25 07:12

Erik Funkenbusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!