一、EF日期格式筛选,获取本年,本月,本日等

1.直接使用DateTime的部分值相等

//获取上一个月
            DateTime date = DateTime.Now.AddMonths(-1);
            int count = _context.students.Where(q => 
            q.sbirthday.Value.Year == date.Year
            &&q.sbirthday.Value.Month== date.Month
            ).Count();

2.使用时间短筛选

//获取上2个月到今天
DateTime start = DateTime.Now.AddMonths(-2);
DateTime end = DateTime.Now;
List<student> list = _context.students.Where(q => q.sbirthday >= start && q.sbirthday < end)
    .ToList();
Console.WriteLine(list.Count);

二、EF日期格式筛选,方式2 ,使用SqlFunctions

在EF中日期筛选需要使用SqlFunctions,特别需要注意一下命名空间

namespace System.Data.Entity.SqlServer
{
    //
    // 摘要:
    //     包含在 Linq to Entities 中公开 SqlServer 方法的函数存根。
    public static class SqlFunctions


时间差计算函数,对应SqlServer数据库的DATEDIFF函数

        //
        // 摘要:
        //     返回所指定开始日期和结束日期之间的指定日期部分边界的计数。
        //
        // 参数:
        //   datePartArg:
        //     要计算时间间隔差值的日期部分。
        //
        //   startDate:
        //     第一个日期。
        //
        //   endDate:
        //     第二个日期。
        //
        // 返回结果:
        //     两个日期之间的时间间隔数。
        [DbFunction("SqlServer", "DATEDIFF")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "startDate")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "endDate")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "datePartArg")]
        public static int? DateDiff(string datePartArg, DateTime? startDate, DateTime? endDate);
关于DATEDIFF函数,计算差值为指定类型的总差值:

	select DATEDIFF(day,'2016-1-1','2017-1-1');
	select DATEDIFF(month,'2016-1-1','2017-1-1');
        select DATEDIFF(year,'2016-1-1','2017-1-1');

注:对应需要判断大于多少天或月的处理逻辑需要使用表达式>数字,例如:大于3天的记录 DATEDIFF(Day,'xx','xx')>3
判断少于多少天需要表达式<=数字

使用实例:

DateTime date = DateTime.Now.AddMonths(-1);
//本年
int count1 = _member.DbSet.Where(q => SqlFunctions.DateDiff("year", q.ActiveTime, date) == 0).Count();
//本月
int count2 = _member.DbSet.Where(q => SqlFunctions.DateDiff("month", q.ActiveTime, date) == 0).Count();
//本天
int count3 = _member.DbSet.Where(q => SqlFunctions.DateDiff("day", q.ActiveTime, date) == 0).Count();

自动生成的Sql代码:

exec sp_executesql N'SELECT 
[Extent1].[ActiveAmount] AS [ActiveAmount]
FROM [dbo].[Member_Info] AS [Extent1]
WHERE ([Extent1].[IsActive] = 1) 
AND (0 = (DATEDIFF(day, [Extent1].[ActiveTime], @p__linq__0)))',N'@p__linq__0 datetime2(7)',@p__linq__0='2017-01-02 00:00:00'


更多参考:

sqlserver计算时间差DATEDIFF 函数

EF日期筛选异常:SqlServer.DATEDIFF”函数的 DATEPART 参数必须是文字字符串。

http://blog.163.com/m13864039250_1/blog/static/21386524820141184595445/


本文转载:CSDN博客