简体   繁体   English

实体框架可序列化事务死锁

[英]Entity Framework Serializable Transaction Deadlock

I have to insert a row into the database but the problem is that the primary key is generated based on the total counts of rows. 我必须在数据库中插入一行,但是问题是主键是基于行的总数生成的。 Eg if the db has 25601 rows, the ID of the newly inserted record would be CT25602. 例如,如果数据库有25601行,则新插入的记录的ID将为CT25602。

I want to use transactions for primary key collisions. 我想将事务用于主键冲突。 Here is the code I wrote. 这是我写的代码。

public void CreateContact(ContactViewModel input)
{
    var transactionScopeOptions = new TransactionOptions
    {
        IsolationLevel = IsolationLevel.Serializable,
        Timeout = TimeSpan.MaxValue
    };

    using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transactionScopeOptions))
    {
        var contactNo = GenerateIdentity();
        var contact = MapContactFields(new NavContact { No_ = contactNo }, input);

        _db.Contacts.InsertOnSubmit(contact);
        _db.SubmitChanges();
        transaction.Complete();
    }
}

This code gives me deadlocks if two persons are trying to insert a contact in a small timespan. 如果两个人试图在较短的时间间隔内插入联系人,此代码给我带来僵局。

Any suggestions ? 有什么建议么 ? Thank you 谢谢

Yes, the scenario you described is very likely to deadlock. 是的,您描述的场景很可能会陷入僵局。 I would recommend using a sequence instead. 我建议改用序列 If not, then one solution is to acquire an exclusive app lock in the transaction, before scannig for the next identity. 如果不是,那么一种解决方案是扫描下一个身份之前 ,在事务中获取独占应用程序锁定。 See sp_getapplock . 请参见sp_getapplock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM