Entity Framework 6 ToString(), formatting (DateTime format), query intercept

后端 未结 2 1263
轻奢々
轻奢々 2021-01-22 15:40

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

db.Items.Where(x => x.DateTime1.ToSt         


        
2条回答
  •  孤城傲影
    2021-01-22 16:39

    1. Function in MS SQL
    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. Create sql execution Interceptor
    public class DbCommandInterceptor  : IDbCommandInterceptor 
    {
        public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext)
        {
            if (command.CommandText.IndexOf("CAST") != -1)
            {
                command.CommandText = command.CommandText.Replace("CAST(", "dbo.ToString(");
                command.CommandText = command.CommandText.Replace("] AS nvarchar(max))", "])");
    
            }
        }
    

    }

    1. Add Interceptor to DbContext
    public class DB : DbContext
    {
        public DB(): base(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=EFTest")
        {
            DbInterception.Add(new DbCommandInterceptor ());
        }
    }
    

提交回复
热议问题