如何使用LINQ查询为日期添加小时数?[英] How to add hours to date using LINQ query?

本文是小编为大家收集整理的关于如何使用LINQ查询为日期添加小时数?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要获得最后七个日期,并从数据库中添加-4小时

我的SQL查询将是:

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]) 

任何人都可以帮助我将此SQL查询转换为Linq?

推荐答案

我想您正在使用C#?请查看以下内容是否适合您的需要:

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;

其他推荐答案

尚未编译它,只是尝试此

 var yourRecord =  DBContext.Table.Where(x => DbFunctions.AddDays(DateTime.Now, -7) <= x.YourDate && x.YourDate <= DateTime.Now).FirstOrDefault();
       yourRecord.YourDate = DateTime.Now.AddHours(4);

本文地址:https://www.itbaoku.cn/post/1556795.html

问题描述

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 ?

推荐答案

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;

其他推荐答案

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);