我们有一个使用EF4作为数据访问层的ASP.Net MVC应用程序,我们看到了一些意外的行为,涉及到OptimisticConcurrencyExceptions没有在我们认为它们应该被抛出的情况下被抛出。
我们已经将问题简化为以下代码...
这是我们的MVC应用程序中发生的简单版本,但同样的问题也会出现。
当我们在thirdEntities上调用SaveChanges时,我期望会出现异常,但实际上没有任何异常被抛出。
更有趣的是,当我们附加SQL Profiler时,我们看到Version被用作where子句,但使用的是thirdEntities Version值(数据库中的当前值),而不是firstEntities的值,尽管它是在调用SaveChanges之前明确设置的。 SaveChanges正在将Version重置为检索到的值而不是设置的值。
在EDMX中,Version被设置为具有StoreGeneratedPattern设置为Computed。
有人知道这里发生了什么吗?
我们已经将问题简化为以下代码...
using System.Linq;
using Project.Model;
namespace OptimisticConcurrency
{
class Program
{
static void Main()
{
Contact firstContact = null;
using (var firstEntities = new ProjectEntities())
{
firstContact = (from c in firstEntities.Contacts
where c.LastName == "smith" select c).Single();
}
using (var secondEntities = new ProjectEntities())
{
var secondContact = (from c in secondEntities.Contacts
where c.LastName == "smith" select c).Single();
secondContact.Title = "a";
secondEntities.SaveChanges();
}
firstContact.Title = "b";
using (var thirdEntities = new ProjectEntities())
{
var thirdContact = (from c in thirdEntities.Contacts
where c.LastName == "smith" select c).Single();
thirdContact.Title = firstContact.Title;
//EXPLICITLY SET VERSION HERE
thirdContact.Version = firstContact.Version;
thirdEntities.SaveChanges();
}
}
}
}
这是我们的MVC应用程序中发生的简单版本,但同样的问题也会出现。
当我们在thirdEntities上调用SaveChanges时,我期望会出现异常,但实际上没有任何异常被抛出。
更有趣的是,当我们附加SQL Profiler时,我们看到Version被用作where子句,但使用的是thirdEntities Version值(数据库中的当前值),而不是firstEntities的值,尽管它是在调用SaveChanges之前明确设置的。 SaveChanges正在将Version重置为检索到的值而不是设置的值。
在EDMX中,Version被设置为具有StoreGeneratedPattern设置为Computed。
有人知道这里发生了什么吗?