C# 如何更改实体框架为Datetime生成SQL精度的方式

C# 如何更改实体框架为Datetime生成SQL精度的方式,c#,sql-server,entity-framework,datetime,C#,Sql Server,Entity Framework,Datetime,我有一个表use id&DateTime列作为主键,但当我尝试按实体框架更新数据时,如下所示: using (Entities context = new Entities()) { var item = (from item in context.BatchData where item.Id == 2 select item ).FirstOrDefault(); item.Title = "EF6TEST";

我有一个表use id&DateTime列作为主键,但当我尝试按实体框架更新数据时,如下所示:

using (Entities context = new Entities())
{
    var item = (from item in context.BatchData
                where item.Id == 2
                select item ).FirstOrDefault();

    item.Title = "EF6TEST";

    context.SaveChanges();
}
我犯了一个错误

Store update、insert或delete语句影响了意外的行数(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'
因此,原因是SQL中的参数是
@2='2017-09-16 11:29:35.3720000'
,精度是7,应该是
@2='2017-09-16 11:29:35.372'


这是我的问题,如何解决

您可以使用
IDB interceptor
更改所需数据,下面是一个将参数类型从
DateTime2
更改为
DateTime
的interceptor示例,您可以将其扩展为在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;
        }
    }
公共类DateInterceptor:IDbInterceptor,IDbCommandInterceptor
{
public void ReaderExecuting(DbCommand,
DbCommandInterceptionContext(截取上下文)
{
var dateParameters=command.Parameters.OfType()
其中(p=>p.DbType==DbType.DateTime2);
foreach(dateParameters中的var参数)
{
parameter.DbType=DbType.DateTime;
}
}
要使用它,请将
DbInterception.add(new DateInterceptor());
添加到dbContext类的
OnModelCreating
的末尾

生成的SQL将从

@日期时间2(7)“@0=0,@1=1,@2='2017-09-2414:41:33.7950485”

@日期时间',@0=0,@1=1,@2='2017-09-2414:40:32.327'


我猜这是SQL 2016或Azure SQL数据库

看到这个问题了吗


SQL 2016已经改变了datetime和datetime2之间转换的工作方式。要用于乐观并发,您最好使用datetime2(7)。

您的SQL server使用什么数据类型?datetime还是datetime2?我的SQL server使用DateTimeSQL server中的datetime精度为毫秒(.fff)因此,sql server端的.372是正确的,但是,.NET DateTime将返回7的精度,您可以将数据类型更新为DateTime2吗?恐怕我无法更改,是否可以更改生成器sql?非常感谢,我尝试了DATETERCEPTOR。它成功了