7

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M.Nabeel
  • 1,066
  • 7
  • 19

1 Answers1

3

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();
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Error : 'System.Nullable' does not contain a definition for 'TotalSeconds' and no extension method 'TotalSeconds' accepting a first argument of type 'System.Nullable' could be found (are you missing a using directive or an assembly reference?) – M.Nabeel May 26 '16 at 05:33
  • @M.Nabeel ah, so your `e.EndTo` is a `Nullable` `TimeSpan`, in that case, please try to use `e.EndTo.Value.TotalSeconds` instead – Ian May 26 '16 at 06:02
  • @M.Nabeel no problem! ;) – Ian May 26 '16 at 06:37
  • This doesn't work for Linq to Entities. "'TotalSeconds' is not supported in LINQ to Entities". Additionally `TotalSeconds` is a `double` but `AddSeconds` takes an `int` so it won't even compile as written. – xr280xr Jan 14 '20 at 23:35