简体   繁体   中英

i got this exception in .net when try to compare date in linq

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

var tripss = context.trips.Join(context.UserMasters, t => t.DriverId, u => u.UserID,
                (tr, us) => new
                {
                    DateOfTrip = DbFunctions.TruncateTime(tr.DateOfTrip),
                    DriverId = tr.DriverId,
                    FromCity = tr.FromCity,
                    ID = tr.ID,
                    PlaceToMeet = tr.PlaceToMeet,
                    TimeOfTrip = tr.TimeOfTrip,
                    ToCity = tr.ToCity,
                    Name = (us.FullName == null) ? us.UserName : us.FullName,
                    ImageUrl = us.ImageUrl,
                    PostTime=(DbFunctions.TruncateTime( tr.TimeOfPost)==DateTime.Now.Date)?
                    (tr.TimeOfPost.Value.Hour==DateTime.Now.Hour)? (DbFunctions.DiffMinutes(DateTime.Now,tr.TimeOfPost).Value)
                    : DbFunctions.DiffHours(DateTime.Now,tr.TimeOfPost).Value : DbFunctions.DiffDays(DateTime.Now, tr.TimeOfPost).Value


                }).ToList();

the answer is in this code DbFunctions.TruncateTime( tr.TimeOfPost)==DateTime.Now.Date) when using datetime.now in linq expressions we cant use date property in datetime class removing.date solved the problem

For this query you can move the date time variables outside the query.

var dt =    DateTime.Now.Date;
var now = DateTime.Now;
var hour = DateTime.Now.Hour;



    var tripss = context.trips.Join(context.UserMasters, t => t.DriverId, u => u.UserID,
                    (tr, us) => new
                    {
                        DateOfTrip = DbFunctions.TruncateTime(tr.DateOfTrip),
                        DriverId = tr.DriverId,
                        FromCity = tr.FromCity,
                        ID = tr.ID,
                        PlaceToMeet = tr.PlaceToMeet,
                        TimeOfTrip = tr.TimeOfTrip,
                        ToCity = tr.ToCity,
                        Name = (us.FullName == null) ? us.UserName : us.FullName,
                        ImageUrl = us.ImageUrl,
                        PostTime=(DbFunctions.TruncateTime( tr.TimeOfPost)== dt)?
                        (tr.TimeOfPost.Value.Hour== hour)? (DbFunctions.DiffMinutes(now, tr.TimeOfPost).Value)
                        : DbFunctions.DiffHours(now, tr.TimeOfPost).Value : DbFunctions.DiffDays(now, tr.TimeOfPost).Value
    
    
                    }).ToList();

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