Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Datetime and time in Entity Framework from separate column

I want to get all the events which are not ended yet

select * FROM [Events] where EndDate+cast(EndTo as datetime)>GETDATE() 

which is working perfectly.

This is my value in (EndTo: 11:00:00.0000000, END DATE: 2016-05-26)

I tried using

var list = dbContext.Events
                    .Where(e => e.EndDate + e.EndTo > DateTime.Now)
                    .ToList();

and I'm getting an error

DbArithmeticExpression arguments must have a numeric common type.

How can I write this query in Entity Framework?

like image 458
M.Nabeel Avatar asked May 26 '16 05:05

M.Nabeel


1 Answers

This is because you try to add DateTime with TimeSpan, which is not allowed. To do that, try to use something like DateTime.AddSeconds(TimeSpan.TotalSeconds) instead:

var list= dbContext.Events
           .Where(e=>e.EndDate.AddSeconds(e.EndTo.TotalSeconds) > DateTime.Now)
           .ToList();

Or if this is LINQ to Entities:

var list= dbContext.Events
           .Where(e=>EntityFunctions.AddSeconds(e.EndDate, e.EndTo.TotalSeconds) > DateTime.Now)
           .ToList();

Edit:

Since your e.EndTo is a Nullable<TimeSpan>, then you should use its Value:

var list= dbContext.Events
           .Where(e=>e.EndDate.AddSeconds(e.EndTo.Value.TotalSeconds) > DateTime.Now)
           .ToList();

Or

var list= dbContext.Events
           .Where(e=>EntityFunctions.AddSeconds(e.EndDate, e.EndTo.Value.TotalSeconds) > DateTime.Now)
           .ToList();
like image 199
Ian Avatar answered Oct 16 '22 07:10

Ian