How to add hours to date using LINQ query?

2019-07-21 09:54发布

I need to get the last seven dates and add -4 hours to each date from my database

My SQL Query will be :

select DATEADD(hh, -4, [DateColumn]) 
from mydatabse.dbo.mytable
where DATEDIFF(dd, DATEADD(hh, -4, [DateColumn]), getdate()) between 1 and 7
group by DATEADD(hh, -4, [DateColumn]) 

Could anyone help me to convert this SQL query to LINQ ?

3条回答
我想做一个坏孩纸
2楼-- · 2019-07-21 10:20

I suppose you're using C#? Please see if the following fits your need:

using System.Data.Entity.SqlServer;

from a in mydatabase.mytable
let d = SqlFunctions.DateAdd("hh", -4, a.DateColumn)
let e = SqlFunctions.DateDiff("dd", d, SqlFunctions.GetDate())
where e >= 1 && e <= 7
group a by d into g
select g.Key;
查看更多
甜甜的少女心
3楼-- · 2019-07-21 10:21

Haven't compiled it just try this

 var yourRecord =  DBContext.Table.Where(x => DbFunctions.AddDays(DateTime.Now, -7) <= x.YourDate && x.YourDate <= DateTime.Now).FirstOrDefault();
       yourRecord.YourDate = DateTime.Now.AddHours(4);
查看更多
Summer. ? 凉城
4楼-- · 2019-07-21 10:29

What's seems to be the problem? DateTime Type have AddHours() method so you can use it.

If you want to change property in your table it will be like this:

var entity = context.Table.FirstOrDefault(); // get your entity
entity.YourDate = entity.YourDate.AddHours(4); //add 4 hours
context.SubmitChanges(); //Save it to you storage
查看更多
登录 后发表回答