将sql转换为linq,其中包含传入的日期和时间。需要加时间HH

时间:2017-02-15 20:21:49

标签: sql linq datetime linq-to-sql linq-to-entities

这是在日期和时间(24小时时间)中传递的SQL Server sql语句

declare @date varchar(10) = '2-15-2017'
declare @time varchar(2) = '11'
declare @timeExt varchar(3) = ':00'


--declare @mytime datetime = '2-15-2017 11:00'
declare @mytime datetime = @date + ' ' + @time + @timeExt

select * from [dbo].[QAList] Q
where q.CreatedDateTime between dateadd(hh,-1, @mytime) and @mytime 

然后对于Linq to SQL(实体)我只做了Date,但我需要在时间中添加

string dateIn = "2-15-2017";
DateTime d = DateTime.Parse(dateIn);

注意.Where

   var query =  QALists
    .Where (z => z.CreatedDateTime >= d )
    .AsEnumerable()
    .Select(z => new QAList()
                {
                    Agent = z.Agent,
                    ClientName = z.ClientName,
                    Disposition = z.Disposition,
                    CallDate = z.Calldate,
                    Comment = z.Comment,
                    CreatedDateTime = z.CreatedDateTime,
                    CallLength = z.CallLength,
                    IdentityColumnId = z.IdentityColumnId,
                    Number = z.Number,
                    InboundCall = z.InboundCall,
                    OutboundCall = z.OutboundCall,
                    Status = z.Status,
                    QAListId = z.QAListId     
                }).ToList();

1 个答案:

答案 0 :(得分:1)

问题中没有LINQ特定的内容 - 只需创建包含所需范围的两个DateTime变量(如您所知,DateTime数据类型包含日期和时间):

var endTime = new DateTime(2017, 02, 15, 11, 00, 00);
var startTime = endTime.AddHours(-1);

然后只需在查询条件中使用它们:

.Where (z => z.CreatedDateTime >= startTime && z.CreatedDateTime <= endTime)