实体框架6 ToString(),格式(DateTime格式),查询拦截 [英] Entity Framework 6 ToString(), formatting (DateTime format), query intercept

查看:49
本文介绍了实体框架6 ToString(),格式(DateTime格式),查询拦截的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在日期时间(DateTime?)字段中找不到使用linq2sql搜索的正确方法.

I`m not found correct way to search with linq2sql in DateTime (DateTime?) fields.

db.Items.Where(x => x.DateTime1.ToString().Contains("2014.08"))

不起作用,因为在linq2sql中创建 CAST([XXXX.DateTime1] AS NVARCHAR(MAX))= '04 Aug 2014'NOT 2014.08

Not work, because in linq2sql create CAST([XXXX.DateTime1] AS NVARCHAR(MAX)) = '04 Aug 2014' NOT 2014.08

我尝试使用自定义函数映射,但没有结果

I try use custom function mapping, but no result

推荐答案

为什么不只使用Year and Month属性?您应该能够将输入的字符串转换为Year and Month数字.然后,您将执行以下操作:

Why don't you just use the Year and Month property? You should be able to convert the string input into Year and Month number. Then you do something like:

db.Items.Where(x => 
   x.DateTime1.Value.Year == 2014 
   && x.DateTime1.Value.Month == 8)

它将简单地转换为:

WHERE (2014 = (DATEPART (year, [Extent1].[Date]))) 
AND     (8 = (DATEPART (month, [Extent1].[Date])))

更新

您可以使用 SqlFunctions.DatePart

update

You can use SqlFunctions.DatePart and DbFunctions.Right to produce following format yyyy.mm.dd.

db.Items.Where(x => 
    (SqlFunctions.DatePart("yyyy", x.DateTime) + "."
    + DbFunctions.Right("0" + SqlFunctions.DatePart("m", x.DateTime1), 2) + "."
    + DbFunctions.Right("0" + SqlFunctions.DatePart("d", x.DateTime1), 2))
    .Contains("2014.08"));

这篇关于实体框架6 ToString(),格式(DateTime格式),查询拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆