I am confused to understand the difference between Linq's Count()
for IQueryable
and Linq's Count()
for IEnumerable
.
I have the following method which has to return the same result of the counts, but enumerableCount
equals 2 while queryableCount
is 0:
public List<int> GetMembersCount()
{
var queryableQuery = MemberRepository.GetAll().Include(p => p.Message);
var enumerableQuery = MemberRepository.GetAll().Include(p => p.Message).ToList();
var queryableCount = queryableQuery.Count(m => m.Message.Deadline.Date == DateTime.Today);
var enumerableCount = enumerableQuery.Count(m => m.Message.Deadline.Date == DateTime.Today);
return new List<int>
{
enumerableCount,
queryableCount
};
}
Can anybody explain what is going on? I am using PostgreSQL and Entity Framework
CodePudding user response:
Try
var querableCount = querableQuery
.Count(m => DbFunctions.TruncateTime(m.Message.Deadline) == DbFunctions.TruncateTime(DateTime.Now));
because DateTime.Date
doesn't seem to be supported in EF if used in lambda expressions: https://stackoverflow.com/a/21825268/284240
CodePudding user response:
I don't use dates in filtering due to problems I've had in the past.
var dt = DateTime.Today;
var dt_ole = Convert.ToInt32(dt.ToOADate());
var queryableCount = queryableQuery.Count(m => SqlFunctions.DateDiff("DD", "1899-12-30", m.Message.Deadline) == dt_ole);