了解实体框架乐观并发(数据库获胜)模式

Dee*_*ain 6 entity-framework optimistic-concurrency

请参阅使用Reload解决乐观并发异常(数据库获胜):

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);
    blog.Name = "The New ADO.NET Blog";
    bool saveFailed;
    do
    {
        saveFailed = false;

        try
        {
            context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            saveFailed = true;

            // Update the values of the entity that failed to save from the store
            ex.Entries.Single().Reload();
        }

    } while (saveFailed);
}
Run Code Online (Sandbox Code Playgroud)

为什么该方法SaveChanges()被调用Reload()?此调用永远不会更改数据库中的数据.

Ger*_*old 3

我同意这还不太清楚。这段代码的意图就在这句话中

然后,该实体通常会以某种形式返回给用户,他们必须尝试再次进行更改并重新保存。

所以如果他们添加评论会更好:

...
// User evaluates current values and may make new changes.
try
{
    context.SaveChanges();
}
...
Run Code Online (Sandbox Code Playgroud)