我如何停止的DateTimeOffset规模由造成ChangeConflictException中的LINQ to SQL?规模、ChangeConflictException、DateTimeOff

由网友(素染倾城色)分享简介:下面code尝试创建一个新的记录,然后修改它后,它已被提交到数据库。最后的SubmitChanges()调用抛出一个ChangeConflictException。The following code tries to create a new record and then modify it after it h...

下面code尝试创建一个新的记录,然后修改它后,它已被提交到数据库。最后的SubmitChanges()调用抛出一个ChangeConflictException。

The following code tries to create a new record and then modify it after it has been committed to the database. The last SubmitChanges() call throws a ChangeConflictException.

ItemA itemA = new ItemA();
itemA.Foo = "a";
itemA.Created = DateTimeOffset.Now.UtcDateTime;

ItemAs.InsertOnSubmit(itemA);
SubmitChanges();

itemA.Foo = "b";
SubmitChanges();

通过研究我发现,创造列是冲突的,即使报道CurrentValue的和DatabaseValue出现相同的dataContext.ChangeConflicts。在仔细检查我发现蜱略有不同。因为我已经设置的DateTimeOffset列在数据库中有一个规模为3,即毫第二,它是不一样的.NET版本,我相信有规模的7。因此LINQ到SQL中的价值注意到的不匹配,认为之间的插入和更新上面显示,事情已经修改了数据库。

By examining the dataContext.ChangeConflicts I found that the 'Created' column was in conflict, even though the reported CurrentValue and DatabaseValue appeared identical. On closer inspection I found that the Ticks were slightly different. Because I have set the DateTimeOffset column in the database to have a scale of 3, i.e. to the milli second, it is not the same as .NET's version of the value which I believe has a scale of 7. As a result Linq to Sql notices the mismatch and thinks that between the insert and update shown above, something has modified the database.

除了写一个extentension方法或东西,我可以用它来修改precision在.NET中有没有更好的方式来处理这个?

Aside from writing an extentension method or something that I can use to modify the precision in .NET is there a better way to deal with this?

更新

我不得不依靠它必须设置该模型的DateTimeOffset列时,称为扩展方法。

I have had to rely on an extension method which must be called when setting DateTimeOffset columns on the model.

public static DateTimeOffset ToUniversalTime(this DateTimeOffset dto, int scale) {
    DateTimeOffset utc = dto.ToUniversalTime();
    return utc.AddTicks(-(utc.Ticks % (int)Math.Pow(10, 7 - scale)));
}

然后可以称为:

Which can then be called as:

EntityFoo.Created = DateTimeOffset.Now.ToUniversalTime(3)

我真的不喜欢这种方法,因为这意味着我必须手动设置我相信数据方面应该做的规模。

I don't really like this approach as it means I have to manually set the scale which I believe the data context should be doing.

推荐答案

由于你总是用世界时,我看不到有什么优势的DateTimeOffset为您提供了日期时间。你可以使用DateTime.UtcNow,具有相同的precision作为SQL Server的日期时间。

As you're always using Universal Time, I can't see what advantage DateTimeOffset gives you over DateTime. You could use DateTime.UtcNow, which has the same precision as Sql Server's DateTime.

另外,如您使用的是SQL Server 2008中,您可以在字段中存储为DATETIME2在数据库中:这有您所需要的额外精度

Alternatively, as you're using Sql Server 2008, you could store your field as a DateTime2 in the database: this has the additional accuracy you require.

阅读全文

相关推荐

最新文章