简体   繁体   中英

Entity Framework DateTime Comparison in Query - Possible Bug?

Suppose you have a database table such that

public partial class myTable
{
    [Key]
    public Guid rowID { get; set; }

    [Column(TypeName = "datetime2")]
    public DateTime? eventTime { get; set; }
}

Now suppose you're looking for a data in there that has happened 5 or fewer days ago:

DateTime dTVal = DateTime.Now.AddDays(-5);
var event = db.myTable.Where(evt => evt.eventTime >= dTVal);

The above query will NOT work. The reason being is that DateTime.Now gives hours, minutes and seconds of course. However, instead of giving an error from sql or the like the results are just returned with 0 rows.

In order to resolve and retrieve the expected data:

var dtVal = DateTime.Now.AddDays(-5).Date; // This wouldn't work in the LINQ to Entities query because AddDays() method...
var events = db.myTable.Where(evt => evt.eventTime >= dtVal);

Perhaps my relative newness with EF is to blame, but this seems VERY unintuitive and somewhat a pain, because Intellisense doesn't pick it up as anything other than DateTime? and the hover tooltip on the property is also DateTime? myTable.eventTime... DateTime? myTable.eventTime... thereby causing me to have to go find every date property I am comparing against to make sure I a converting that correctly.

Should not EF take the DateTime object in this case and convert it to the correct format prior to constructing the query, and throw an exception prior actually performing the query?

Does anyone have a familiarity with this type of problem and what have you done in the past to work with it?

Similar Answered Question

Workaround is to use a DateTime.Date for date2 type entities.

var compareDate = DateTime.Now.AddDays(-5).Date;

Thanks.

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