我有一个程序在两台服务器上重复运行。 我需要选择和更新程序中的DB记录,所以我需要EF锁定表或事务,否则程序的每个副本都可以选择和修改相同的记录。第一个副本使数据库发生更改时,另一个不应运行相同的代码部分。实体框架事务
我在EF中发现了TransactionScope,但它无法正常工作,因为在第一个副本运行时,我可以在SQL Server MGM工作室中对该表进行多次选择和更新。
我有一个简短的代码片段,请验证它:
using (TransactionScope transaction = new TransactionScope())
{
//select some records which aren't locked by the other copy of the program
//condition: Locked==null
recipientsList = (from c in context.Recipients
where
c.SentToPlatform == false && c.PopupID != null &&
c.Message.MessageStatus == 2 && c.Locked == null
select c).Take(piecePerMinute).ToList();
foreach (var recipient in recipientsList)
{
//i need make some changes on the record, prevent it from the other copy of program
//I need to change locked column to true
recipient.Locked = true;
recipient.LockBy = ipAddress;
Console.Write("I");
Thread.Sleep(1000);
}
//close transaction
try
{
context.SaveChanges();
transaction.Complete();
} catch (Exception ex)
{
}
}
在这一点上,你有3个合理的答案。所有三个答案都集中在同一件事上,但从你的意见看来,我们没有达到你想要的。我认为你应该花一些**质量时间来考虑你的问题以及如何清楚地表达它。 – EBarr 2012-02-02 13:45:52