The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties - linq

Using this code in Entity Framework I receive the following error. I need to get all the rows for a specific date, DateTimeStart is of type DataType in this format 2013-01-30 12:00:00.000
Code:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => x.DateTimeStart.Date == currentDateTime.Date);
Error:
base {System.SystemException} = {"The specified type member 'Date' is
not supported in LINQ to Entities. Only initializers, entity members,
and entity navigation properties are supported."}
Any ideas how to fix it?

DateTime.Date cannot be converted to SQL. Use EntityFunctions.TruncateTime method to get date part.
var eventsCustom = eventCustomRepository
.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);
UPDATE: As #shankbond mentioned in comments, in Entity Framework 6 EntityFunctions is obsolete, and you should use DbFunctions class, which is shipped with Entity Framework.

You should now use DbFunctions.TruncateTime
var anyCalls = _db.CallLogs.Where(r => DbFunctions.TruncateTime(r.DateTime) == callDateTime.Date).ToList();

EntityFunctions is obsolete. Consider using DbFunctions instead.
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => DbFunctions.TruncateTime(x.DateTimeStart) == currentDate.Date);

I would like to add a solution, that have helpt me to solve this problem in entity framework:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => x.DateTimeStart.Year == currentDateTime.Year &&
x.DateTimeStart.Month== currentDateTime.Month &&
x.DateTimeStart.Day == currentDateTime.Day
);
I hope that it helps.

Always use EntityFunctions.TruncateTime() for both x.DateTimeStart and currentDate.
such as :
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == EntityFunctions.TruncateTime(currentDate));

Just use simple properties.
var tomorrow = currentDateTime.Date + 1;
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
.Where(x => x.DateTimeStart >= currentDateTime.Date
and x.DateTimeStart < tomorrow);
If future dates are not possible in your app, then >= x.DateTimeStart >= currentDateTime.Date is sufficient.
if you have more complex date comparisons, then check Canonical functions
and if you have EF6+ DB functions
More Generally - For people searching for issues Supported Linq methods in EF
can explain similar issues with linq statements that work on Memory base Lists but not in EF.

Simplified:
DateTime time = System.DateTime.Now;
ModelName m = context.TableName.Where(x=> DbFunctions.TruncateTime(x.Date) == time.Date)).FirstOrDefault();

Use the bellow code for using EF6:
(DbFunctions.TruncateTime(x.User.LeaveDate.Value)

I have the same issue with Entity Framework 6.1.3
But with different scenario. My model property is of type nullable DateTime
DateTime? CreatedDate { get; set; }
So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext:
Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);

Another solution could be:
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).AsEnumerable()
.Where(x => x.DateTimeStart.Date == currentDate.Date).AsQueryable();

I've faced this same issue and it seems that it is really caused by the presence of a call to the .Date property within the Where method. When removed, the error disappears. Consider that calling the .Date property on any side of the comparison operator causes this error. Calling the .Date property outside and before the Where method is enough to solve this error.

Related

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.Int32]

I have the following error:
LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1 [System.Int32] get_st_past_enrollment_success()'
method, and this method cannot be translated into a store expression.
This is caused by the following linq
IEnumerable<subject> _subjects = (from subject in context.subjects
where
subject.enrollments.Count() < subject.sj_max_enrollment
&& subject.sj_availability == true
&& !this.get_st_past_enrollment_success().Contains(subject.sj_subject_id)
select subject);
get_st_past_enrollment_success() returns a List:
public List<int> get_st_past_enrollment_success()
{
return this.enrollments.Where(e => e.em_enrolled == false && e.em_result >= 50).Select(e => e.em_subject_id).ToList();
}
What am i doing wrong here?
Your query itself contains the method call - and Entity Framework doesn't know what to do with that. Try extracting the list fetch to before the query:
var enrollments = get_st_past_enrollment_success();
var _subjects = from subject in context.subjects
where subject.enrollments.Count() < subject.sj_max_enrollment
&& subject.sj_availability
&& !enrollments.Contains(subject.sj_subject_id)
select subject;
Also note that get_st_past_enrollment_success violates .NET naming conventions - that won't affect whether the code works, but it'll look odd to other developers who are used to the normal conventions.

date comparison in EF query

I have a EF query in which i'm using lambda expressions, when i try to get the difference between two dates, it throws me exception
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
my query is
var unApprovedLeaves = db.Leaves.Where(l => l.Status.Id == 1 && ((System.DateTime.Now.Date - l.ToDate.Date).TotalDays)==0)
.Include("Employee")
.Include("Employee.Manager")
.ToList();
can anyone tell me how do i get this thing right?
You must use SqlFunctions helper from System.Data.Objects.SqlClient. Try this:
var today = DateTime.Now.Date;
var unApprovedLeaves = db.Leaves.Where(l => l.Status.Id == 1 &&
(SqlFunctions.DateDiff("day", today, l.ToDate))==0)
.Include("Employee")
.Include("Employee.Manager")
.ToList();
In Entity Framework it is recomended to use DbFunctions helper from System.Data.Entity
Try this:
var today = DateTime.Now.Date;
var unApprovedLeaves = db.Leaves.Where(l => l.Status.Id == 1 &&
(DbFUnction.DiffDays(today, l.ToDate))==0)
.Include("Employee")
.Include("Employee.Manager")
.ToList();

DateTime and LinqToEntities

I have DateTime field, which storing date + time. I need to use only date part, so I try:
query = query.Where(p => p.CreatedDateTime.Date == DateStart);
but I get the following error:
The specified type member 'Date' is not supported in LINQ to Entities.
Only initializers, entity members, and entity navigation properties
are supported.
why and how to fix it?
what about this:
query = query.Where(p => EntityFunctions.TruncateTime(p.CreatedDateTime) == DateStart);
You cannot use extension functions in LINQ queries that result in a database hit if Entity Framework has no way to convert this into valid SQL.
There may be a more compact solution but the following should work fine:
query = query.Where(p =>
p.CreatedDateTime.Year == DateStart.Year &&
p.CreatedDateTime.Month == DateStart.Month &&
p.CreatedDateTime.Day == DateStart.Day);

compare the dates with linq

I have this code:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
((DateTime)p.Giorno).Date == ((DateTime)i.Data).Date &&
p.MissioneID == missioneID).Sum(p => p.Costo);
If i launch it i obtain this error:
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
how can i compare the datetimes field without the hours part
thanks
Well this is certainly not the most efficient way to do it, but you can try something like:
i.SpesaVitto = db.TDP_NotaSpeseSezB.Where(p => p.GiornoFine == null &&
(new DateTime((p.Giorno as DateTime).Year, (p.Giorno as DateTime).Month, (p.Giorno as DateTime).Day) == (new DateTime((i.Data as DateTime).Year, (i.Data as DateTime).Month, (i.Data as DateTime).Day) &&
p.MissioneID == missioneID).Sum(p => p.Costo);
Depending on the requirements I would probably implement something cleaner and faster but it would depend on how the dates are stored in your database.
Check out this question it looks like the syntax error may be in your SQL, not in your LINQ. The asker in that question had written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today
SQL ------
When they should have written:
SQL ------
Select
EmployeeNameColumn
From
EmployeeTable
WHERE StartDateColumn <= GETDATE() //Today
SQL -
solution for your problem will be the "SqlFunctions class and DateDiff" http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.aspx

LINQ Dynamic Expression API, predicate with DBNull.Value comparison

I have an issue using the Dynamic Expression API. I cannot seem to compare a DataTable field against DBNull.Value. The API is supposed to be able to "support static field or static property access. Any public field or property can be accessed.". However given the following query:
var whatever = table1.AsEnumerable()
.Join(table2.AsEnumerable(),
(x) => x.Field<int>("Table1_ID"),
(y) => y.Field<int>("Table2_ID"),
(x, y) => new { x, y})
.AsQueryable()
.Where("x[\"NullableIntColumnName\"] == DBNull.Value");
I end up getting the error: "No property or field 'DBNull' exists in type '<>f__AnonymousType0`2'"
Anyone have ideas on how to get around this? I can't use Submission.Field("NullableIntColumnName") in the string passed to the Where method either, btw, or else I would be able to compare against null instead of DBNull.Value.
Well, I finally got it. cptScarlet almost had it.
var values = new object[] { DBNull.Value };
...
.Where("x[\"NullableIntColumnName\"] == #0", values);
or
.Where("x[\"NullableIntColumnName\"] == #0", DBNull.Value);
What happens when you replace your current .Where with something like
.Where(string.format("x[\"NullableIntColumnName\"] == {0}",DBNull.Value));
If you change x.Field<int>("Table1_ID") to x.Field<int?>("Table1_ID") then you'll get nullable integers instead of regular integers, and any DBNull values will be converted to simple C# null values. Based simply on your code snippet, I'm not even sure you'd need dynamic expressions - a simple .Where(foo => foo.x == null) ought to work.
In general, you can also try:
.Where("NullableColumnName.HasValue");
Sorry to non-answer with a USL but...
Have you looked in the source? There's not a lot of it. My guess is that DBNull is not in the list of registered root objects.
I dont have the source to hand right now, but it is also likely to tell you what any other constants one might compare against might be.
.Where(a => a.IntColName == null);
Edit:
Sorry, I did't see this dynamic requirement... Dynamic would be: (at least in Framework 4)
var intColName = "...";
.Where(string.Format("it.{0} is null", intColName));

Resources