linq to sql,按日期数组中的月份和年份匹配日期

时间:2018-01-17 09:25:16

标签: c# sql-server linq

我需要根据日期数组中的月份和年份选择行。

代码:

        int m0 = dates[0].Month;
        int m1 = dates[1].Month;
        int m2 = dates[2].Month;
        int y0 = dates[0].Year;
        int y1 = dates[1].Year;
        int y2 = dates[2].Year;
        var segments = (from sh in context.sh
                         where (sh.Report_Date.Month == m0 && sh.Report_Date.Year == y0 ||
                                sh.Report_Date.Month == m1 && sh.Report_Date.Year == y1 ||
                                sh.Report_Date.Month == m2 && sh.Report_Date.Year == y2)

首先,为此创建6个不同的变量是非常难看的。如果我没有数组计数怎么办?还有另一种方式吗?

2 个答案:

答案 0 :(得分:1)

好的,只是为了完成格式塔:-) 您可以使用System.Data.Entity.DBFunctions转换为不明显的sql函数

DateTime d1 = new DateTime(2015, 01, 01);
DateTime d2 = new DateTime(2016, 05, 01);
DateTime d3 = new DateTime(2017, 03, 01);

var segments = from sh in context.sh
where 
    (DbFunctions.DiffMonths(d1, sh.Report_Date) == 0 || 
    DbFunctions.DiffMonths(d2, sh.Report_Date) == 0 ||
    DbFunctions.DiffMonths(d3, sh.Report_Date) == 0 
    )
select sh;

将被翻译为

SELECT
    [Extent1].[ID] AS [ID],
    [Extent1].[Report_Date] AS [Report_Date],
    [Extent1].[Value] AS [Value]
    FROM [dbo].[sh] AS [Extent1]
    WHERE (0 = (DATEDIFF (month, @p__linq__0, [Extent1].[Report_Date]))) OR (0 = (DATEDIFF (month, @p__linq__1, [Extent1].[Report_Date]))) OR (0 = (DATEDIFF (month, @p__linq__2, [Extent1].[Report_Date])))


-- p__linq__0: '01.01.2015 00:00:00' (Type = DateTime2, IsNullable = false)

-- p__linq__1: '01.05.2016 00:00:00' (Type = DateTime2, IsNullable = false)

-- p__linq__2: '01.03.2017 00:00:00' (Type = DateTime2, IsNullable = false)

答案 1 :(得分:0)

感谢vitalygolub和PredicateBuilder,这就是我所做的:

class Answer(...
    class Meta:
        unique_together = ( 'customuser', 'question' )
    ...