简体   繁体   中英

What is the easiest way to compare DateTime in linq with sql server ce?

I have a sql-server-ce 4 database having a table with a DateTime? column named EndDate. When I delete a record I set this enddate and when I want to retrieve a list of records, I want to filter all the deleted records by applying a filter on the enddate.

I apply this filter via linq using entity framework.

My linq query looks like this:

protected IDbSet<TEntity> Entities;
...
Entities.AsNoTracking().AsQueryable()
  .Where(entity => !entity.EndDate.HasValue || entity.EndDate.Value > DateTime.UtcNow);

When I execute this linq query I get the following error:

The function 'CurrentUtcDateTime' is not supported by SQL Server Compact.

Searching on this error tells me that (if I have understood it correctly) I cannot use DateTime.UtcNow.

My question is: What is the alternative way to reach the goal I try to reach?

Is there a different function I can use via linq? Or should I use a more primitive solution where I also convert the datetime to an Epoch and compare those?

The issue is that the code sample operation is not local to the operation because it is IQueryable state which means it hasn't been executed yet and made into concrete data the process can use. This allows for the query to be adjusted by other operations such as another Where clause if needed.

Once the data is actually queried, Linq creates SQL to do that job and be sent to the database, and that SQL cannot determine what UTC.Now is.

One client option is to make the data concrete, by bringing it down and then filtering it out such as:

Entities.AsNoTracking().ToList()
                       .Where(entity => !entity.EndDate.HasValue 
                                             || entity.EndDate.Value > DateTime.UtcNow);

which will work via the ToList making the data availble to the run-time. The cost is of course bringing down all the values to filter in the client. If that is small, it is fine to do, if it is thousands of records; not advised.


Otherwise the database options are to create a stored procedure to bring down the records needed, or add a computed column field which returns a Boolean for the test(s) needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM