Joyce Koh
Joyce Koh

Reputation: 9

using datetime.add(timespan) with linq but does not work

var newStatusSummary = await(from q in db.QrCode where q.Status == 0 && **q.CreatedDate.Add(offset) * *>=start && **q.CreatedDate.Add(offset) * *<=end
group q by q.CreatedDate.Date into summary
select new {
    Date = summary.Key,
    Total = summary.Count()
}).ToListAsync();

Created date = {1/10/2019 12:00:00 AM}

Offset = {08:00:00}

But I cannot get the newStatusSummary. How Can I work around this?

Upvotes: 0

Views: 1470

Answers (2)

jasonmchoe
jasonmchoe

Reputation: 491

If this is linq to entity framework, replace DateTime.Add() with DateTime.DateAdd():

var newStatusSummary = await (from q in db.QrCode where q.Status == 0
               && **q.CreatedDate.DateAdd(offset)** >= start
               && **q.CreatedDate.DateAdd(offset)** <= end
               group q by q.CreatedDate.Date into summary
               select new
               {
                  Date = summary.Key,
                  Total = summary.Count()
               }).ToListAsync();

Add the using statement using System.Data.Entity.SqlServer;

Edit

Sorry, I did not notice that this was entity framework core. In that case, look at Microsoft.EntityFrameworkCore.DbFunctions class: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbfunctions?view=efcore-3.1

I think you should be able to use the DateDiffDay method to compare dates.

Upvotes: 1

TemaTre
TemaTre

Reputation: 1424

Please use DateAdd instead of Add. The difference is Add - runtime function that works with runtime objects in .Net

DateAdd is special function that maps to Database function. And your request will mapped to SQL request with calling of DATEADD method.

If you use Add method. You should fetch data and convert it to objects before calling of Add method. (But it's bad idea. If threre are a lot of rows in DB it will failed)

Upvotes: 0

Related Questions