Mar*_*Lin 3 c# sql-server datetime entity-framework
我有一个表使用id和DateTime列是pk,但当我尝试通过Entity Framework更新数据时,如下所示:
using (Entities context = new Entities())
{
var item = (from item in context.BatchData
where item.Id == 2
select item ).FirstOrDefault();
item.Title = "EF6TEST";
context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
存储更新,插入或删除语句会影响意外的行数(0).
记录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'
Run Code Online (Sandbox Code Playgroud)
所以,原因是BatchData_CreatedDateTimeSQL中的参数是@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;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它,请添加DbInterception.Add(new DateInterceptor());到OnModelCreatingdbContext类的末尾
生成的SQL将从中更改
@ 2 datetime2(7)',@ 0 = 0,@ 1 = 1,@ 2 ='2017-09-24 14:41:33.7950485'
至
@ 2 datetime',@ 0 = 0,@ 1 = 1,@ 2 ='2017-09-24 14:40:32.327'