Entity Syntax Analysis

I'm trying to execute a LINQ to Entities query (I'm still very new to EF and learning where it differs from LinqToSQL), and I'm trying to do something like this:

DateTime begin = new DateTime(2011, 1, 1); Apps = (from app in context.Instances where app.ReleaseDate.Date == begin select new ScalpApp { Image = app.Image, PublisherName = app.PublisherName, }).ToList(); 

although this works in LinqPad, it is not in my code. Exception Excluded:

 The specified type member 'Date' is not supported in LINQ to Entities. 

Only initializers, entity members, and entity navigation properties are supported.

How to do it in LinqToEF? The field in the DB is a full DateTime (with a timecode), and I'm trying to parse based on date only.

+4
source share
3 answers

You cannot just use 'app.ReleaseDate.Data', but you can:

 var begin = new DateTime(2011, 1, 1); var end = begin.AddHours(24); Apps = (from app in context.Instances where (app.ReleaseDate >= begin) and (app.ReleaseDate < end) select new ScalpApp { Image = app.Image, PublisherName = app.PublisherName, }).ToList(); 
+5
source

It can even use an index in a date field:

 DateTime begin = new DateTime(2011, 1, 1); DateTime end = new DateTime(2011, 1, 2); Apps = (from app in context.Instances where (app.ReleaseDate >= begin) and (app.ReleaseDate < end) select new ScalpApp { Image = app.Image, PublisherName = app.PublisherName, }).ToList(); 
+3
source

EF cannot translate getting the Date part of a DateTime into SQL code. But it has an EntityFunctions.TruncateTime method , which can be translated into the canonical TruncateTime function:

 DateTime begin = new DateTime(2011, 1, 1); Apps = (from app in context.Instances where EntityFunctions.TruncateTime(app.ReleaseDate) == begin select new ScalpApp { Image = app.Image, PublisherName = app.PublisherName, }).ToList(); 
0
source

Source: https://habr.com/ru/post/1334884/


All Articles