1

enter image description here> System.NotSupportedException:“The specified type member 'Date' is not

supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.”

I use EntityFramework6 to Query from Sqlie,there is some worng about dateTime.

var test = DateTime.Now.Date;
var maxEntity=_baseService.GetList<TestNoMapping>(o => o.LastChangeTime.Date == test)
            .OrderByDescending(o => o.SampleId)
            .FirstOrDefault();
public class BaseService
{
    private readonly BaseContext _baseContext = new BaseContext();


    public List<T> GetList<T>(Expression<Func<T, bool>> where) where T : class
    {
        return _baseContext.Set<T>().Where(where).ToList();
    }

the DbFunctions.TruncateTime I have try,But it doesn't work

HuangKai
  • 37
  • 9

3 Answers3

1

The best you can do here is replace the condition by a range test: date between last midnight and midnight today:

var minDate = DateTime.Today;
var maxDate = minDate.AddDays(1);
var maxEntity = _baseService
    .GetList<TestNoMapping>(o => o.LastChangeTime >= minDate
                              && o.LastChangeTime < maxDate)
    .OrderByDescending(o => o.SampleId)
    .FirstOrDefault();

The reason is that it's never a good idea to convert a database value before comparing it: it disables any indexes on the column. (See sargable).

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
0

You have to use DbFunctions.TruncateTime method of Entity framework to match date portion as Linq will not recognize Date property.

Can you try below code?

var test = DateTime.Now;
var maxEntity=_baseService.GetList<TestNoMapping>(o => DbFunctions.TruncateTime(o.LastChangeTime.Date) == DbFunctions.TruncateTime(test))
            .OrderByDescending(o => o.SampleId)
            .FirstOrDefault();
Manprit Singh Sahota
  • 1,279
  • 2
  • 14
  • 37
0

As you see in the exception: Date is not supported in LINQ to Entities

You should use

o => o.LastChangeTime.Year == test.Year &&
     o.LastChangeTime.Month == test.Month &&
     o.LastChangeTime.Day == test.Day &&

instead of

o => o.LastChangeTime.Date == test

Edit

And change

var test = DateTime.Now.Date;

to

var test = DateTime.Now;
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51