c# – 如何更改Entity Framework为Datetime生成SQL精度的方式
发布时间:2020-12-15 23:40:49 所属栏目:百科 来源:网络整理
导读:我有一个表使用id DateTime列是pk,但是当我尝试按实体框架更新数据时,如下所示: using (Entities context = new Entities()){ var item = (from item in context.BatchData where item.Id == 2 select item ).FirstOrDefault(); item.Title = "EF6TEST"; co
我有一个表使用id& DateTime列是pk,但是当我尝试按实体框架更新数据时,如下所示:
using (Entities context = new Entities()) { var item = (from item in context.BatchData where item.Id == 2 select item ).FirstOrDefault(); item.Title = "EF6TEST"; context.SaveChanges(); } 我收到一个错误
记录SQL后,我知道原因. SQL看起来像这样 'update [dbo].[BatchData] set [BatchData_Title] = @0 where (([BatchData_Id] = @1) and ([BatchData_CreatedDateTime] = @2)) select [BatchData_Rowversion] from [dbo].[BatchData]BatchUploadData where @@ROWCOUNT > 0 and [BatchData_Id] = @1 and [BatchData_CreatedDateTime] = @2',N'@0 varchar(30),@1 tinyint,@2 datetime2(7)',@0='EF6TEST',@1=1,@2='2017-09-16 11:29:35.3720000' 所以,原因是SQL中的BatchData_CreatedDateTime参数是@ 2 =’2017-09-16 11:29:35.3720000′,精度是7,它应该是@ 2 =’2017-09-16 11:29:35.372′ . 这是我的问题,如何解决? 解决方法
您可以使用IDbInterceptor来更改所需的数据,这里是一个拦截器的示例,它将参数类型从DateTime2更改为DateTime,您可以扩展它以在DB / DbCommand参数的特定字段上使用它.
public class DateInterceptor : IDbInterceptor,IDbCommandInterceptor { public void ReaderExecuting(DbCommand command,DbCommandInterceptionContext<DbDataReader> interceptionContext) { var dateParameters = command.Parameters.OfType<DbParameter>() .Where(p => p.DbType == DbType.DateTime2); foreach (var parameter in dateParameters) { parameter.DbType = DbType.DateTime; } } 要使用它,请添加DbInterception.Add(new DateInterceptor());到您的dbContext类的OnModelCreating结束 生成的SQL将从中更改
至
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |