本文介绍了如何使用EF 5.0代码第一次启用并发检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我愿做一个检查,然后更新在一个原子操作。我使用的DbContext来管理事务。我期待,如果记录已被另一个线程修改,但没有异常被抛出来得到一个异常。任何帮助,将不胜感激。这里是我的输出:

 线程4:读取... 
线程5:读取...
线程5:更新目标1
线程4:更新目标1
线程4:调用SaveChanges
线程5:调用SaveChanges

下面是我的代码片段:

 公共静态无效的主要(字串[] args)
{
PopulateData();
(新线(UpdateDestination1))启动()。
(新线(UpdateDestination1))启动()。
}

公共静态无效UpdateDestination1()
{
使用(VAR CONTEXT1 =新BreakAwayContext())
{
Console.WriteLine (线程{0}:读......,Thread.CurrentThread.ManagedThreadId);
变种D = context1.Destinations.FirstOrDefault();
Console.WriteLine(线程{0}:更新目标{1},Thread.CurrentThread.ManagedThreadId,d.DestinationId);
d.Name =线程+ Thread.CurrentThread.ManagedThreadId;

{
context1.SaveChanges();
Console.WriteLine(线程{0}:调用SaveChanges,Thread.CurrentThread.ManagedThreadId);
}
赶上(OptimisticConcurrencyException)
{
Console.WriteLine(OptimisticConcurrencyException !!!);
抛出;
}
}
}


解决方案

您可以在一个属性()或IsConcurrencyToken()或.IsRowversion配置时用流利的API(一个属性的)。通常你会在数据库中rowversion列。


I would like to do a check-then-update in an atomic operation. I am using dbcontext to manage the transaction. I was expecting to get an exception if the record has been modified by another thread but no exception is thrown. Any help would be appreciated. Here's my output:

Thread-4: Reading...
Thread-5: Reading...
Thread-5: Updating destination 1
Thread-4: Updating destination 1
Thread-4: SaveChanges
Thread-5: SaveChanges

Here's my code snippet:

public static void Main(string[] args)
{
    PopulateData();
    (new Thread(UpdateDestination1)).Start();
    (new Thread(UpdateDestination1)).Start();
}

public static void UpdateDestination1()
{
    using (var context1 = new BreakAwayContext())
    {
        Console.WriteLine("Thread-{0}: Reading...", Thread.CurrentThread.ManagedThreadId);
        var d = context1.Destinations.FirstOrDefault();
        Console.WriteLine("Thread-{0}: Updating destination {1}", Thread.CurrentThread.ManagedThreadId, d.DestinationId);
        d.Name = "Thread-" + Thread.CurrentThread.ManagedThreadId;
        try
        {
            context1.SaveChanges();
            Console.WriteLine("Thread-{0}: SaveChanges", Thread.CurrentThread.ManagedThreadId);
        }
        catch (OptimisticConcurrencyException)
        {
            Console.WriteLine("OptimisticConcurrencyException!!!");
            throw;
        }
    }
}
解决方案

You can use ConcurrencyCheck annotation on a property ( http://msdn.microsoft.com/en-us/data/gg193958.aspx ) or IsConcurrencyToken() or .IsRowversion when configuring a property with fluent API ( http://msdn.microsoft.com/en-us/data/jj591617#1.12). Typically you would have a rowversion column in the database.

这篇关于如何使用EF 5.0代码第一次启用并发检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:35