实体框架6 ToString(),格式化(DateTime格式),查询拦截

时间:2014-08-07 10:40:17

标签: entity-framework linq-to-sql mapping

我找不到在DateTime(DateTime?)字段中使用linq2sql进行搜索的正确方法。

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

不起作用,因为在linq2sql中创建 CAST([XXXX.DateTime1] AS NVARCHAR(MAX))='2014年8月4日'不2014.08

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

2 个答案:

答案 0 :(得分:3)

为什么不使用年份和月份属性?您应该能够将字符串输入转换为年份和月份编号。然后你做了类似的事情:

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.DatePartDbFunctions.Right生成以下格式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"));

答案 1 :(得分:0)

  1. MS SQL中的函数
  2. CREATE FUNCTION [dbo].[ToString](@P sql_variant)
    RETURNS NVARCHAR(20)
    AS
    BEGIN
        IF (sql_variant_property(@P, 'BaseType') = 'datetime')
            RETURN CONVERT(NVARCHAR(10), @P, 102) + ' ' + CONVERT(NVARCHAR(8), @P, 108);
    
    RETURN CAST(@P as NVARCHAR(max));
    END
    
    1. 创建sql执行拦截器
    2. public class DbCommandInterceptor  : IDbCommandInterceptor 
      {
          public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
          {
              if (command.CommandText.IndexOf("CAST") != -1)
              {
                  command.CommandText = command.CommandText.Replace("CAST(", "dbo.ToString(");
                  command.CommandText = command.CommandText.Replace("] AS nvarchar(max))", "])");
      
              }
          }
      

      }

      1. 将拦截器添加到DbContext
      2. public class DB : DbContext
        {
            public DB(): base(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=EFTest")
            {
                DbInterception.Add(new DbCommandInterceptor ());
            }
        }