将SQL转换为LINQ:将结果选择为模型

时间:2013-03-13 10:51:21

标签: c# sql linq linq-to-sql linq-to-entities

我对LINQ不熟悉,任何人都可以帮助我吗? 提前谢谢。

我的模特:

public class OrderOverViewModel
{
    public int Quantity { get; set; }
    public String ACCN { get; set; }
    public DateTime OrderDate { get; set; }
}

这就是SQL:

SELECT COUNT(*) AS HowMany, 
       DATEADD(dd, 0, DATEDIFF(dd, 0, RXS_OrderDate)) AS OrderDate, 
       RXS_ACCN  AS ACCN  
FROM RXS_RxJobs
WHERE DATEDIFF(WK, RXS_OrderDate, GETDATE()) = 1
GROUP BY RXS_ACCN, DATEADD(dd, 0, DATEDIFF(dd, 0, RXS_OrderDate))

SSMS中的结果:

enter image description here

我希望选择结果填充模型,如何实现这个? 再次感谢。

2 个答案:

答案 0 :(得分:3)

使用SqlFunctions.DateDiff方法在当前日期和订单日期之间获取周数。您也可以通过Date对象的DateTime属性获取日期的日期部分。查询应如下所示:

from j in context.RXS_RxJobs
    .Where(x => SqlMethods.DateDiffDay(x.RXS_OrderDate, DateTime.Now) >= 7 &&
                SqlMethods.DateDiffDay(x.RXS_OrderDate, DateTime.Now) < 14)
group j by new { j.RXS_ACCN, j.RXS_OrderDate.Date } into g
select new OrderOverViewModel
{
   Quantity = g.Count(),
   ACCN =  g.Key.RXS_ACCN,
   OrderDate = g.Key.Date  
};

更新(对于Linq to Entities):

from j in context.RXS_RxJobs
    .Where(x => SqlFunctions.DateDiff("wk", x.RXS_OrderDate, DateTime.Now) == 1)
group j by new { 
    j.RXS_ACCN, 
    Date = EntityFunctions.TruncateTime(j.RXS_OrderDate).Value
} into g
select new OrderOverViewModel {
   Quantity = g.Count(),
   ACCN =  g.Key.RXS_ACCN,
   OrderDate = g.Key.Date 
};

答案 1 :(得分:0)

var viewModels = from job in ObjectContext.RXS_RxJobs
where SqlFunctions.DateDiff("Day", RXS_OrderDate,DateTime.Now) == 1
group job by new { RXS_ACCN, OrderDate} into jobGroup
select new OrderOverViewModel
{ 
    Quantity = jobGroup.Count(),
    ACCN =  jobGroup.Key.RXS_ACCN,
    OrderDate = jobGroup.Key.OrderDate
} ;