.net 未更改实体上的DbUpdateConcurrencyException

.net 未更改实体上的DbUpdateConcurrencyException,.net,sql-server,entity-framework,.net,Sql Server,Entity Framework,似乎我在未修改的实体上遇到了并发异常。我使用的是EntityFramework4.3.1,代码优先,这是在WCF服务中发生的 为了简化我的示例,让我们假设我有两个实体 public class Foo { public int Id { get; set; } public string BarKey { get; set; } public string SomeValue { get; set; } public Bar MyBar { get; set;

似乎我在未修改的实体上遇到了并发异常。我使用的是EntityFramework4.3.1,代码优先,这是在WCF服务中发生的

为了简化我的示例,让我们假设我有两个实体

public class Foo
{
    public int Id { get; set; }
    public string BarKey { get; set; }
    public string SomeValue { get; set; }

    public Bar MyBar { get; set; }
}

public class Bar
{    
    public string Key { get; set; }
    public string OtherValue { get; set; }

    public ICollection<Foo> Foos { get; set; }
}
公共类Foo
{
公共int Id{get;set;}
公共字符串BarKey{get;set;}
公共字符串SomeValue{get;set;}
公共栏MyBar{get;set;}
}
公共类酒吧
{    
公共字符串密钥{get;set;}
公共字符串OtherValue{get;set;}
公共ICollection Foos{get;set;}
}
用户只能通过应用程序编辑FOO。可以查看条形图,但不能编辑。此外,我在WCF服务中使用DTO。典型的应用流程如下所示

  • 客户端调用服务方法
    GetFoo
    。这将从数据库中检索Foo并将其映射到FooDto。这还将检索相关栏并将其映射到BarDto
  • 客户端更新FooDto
  • 客户端调用
    SaveFoo
    ,并将更新的FooDto传递到。
    A.服务将使用
    context.Set().Find(fooDto.Id)
    重新检索原始Foo,然后从fooDto复制更新的值。
    B业务逻辑运行,可以调用
    context.Set().Find(foo.BarKey)
    。可以从Bar读取值,但不会更新。
    C然后,该服务调用
    context.SaveChanged()
  • 此时,我偶尔会得到一个
    DbUpdateConcurrencyException
    。在我的错误处理中,如果异常类型为
    DbUpdateException
    ,它是
    dbupdateeCurrencyException
    的基类,我将循环执行
    ex.Entries
    和log
    entry.Entity.GetType()
    entry.State

    在我的错误日志中,有几个条目显示类型为
    Bar
    ,状态为
    Unchanged
    Bar
    完全有可能已经更新。但是,我不在乎,因为
    Bar
    是不变的

    为什么我会遇到这个异常,以及如何防止它发生?

    可能相关