1

1 つの Datarow のみが作成されることを保証するには、どの Transaction IsolationLevel が最適か。SQL Server 2012 と EntityFramework 6 が使用されていると仮定します。

    using(var db = new XyzContext())
    {
        using(var dbContextTransaction = db.Database.BeginTransaction(???))
        {
            try
            {

                Item obj = db.Item.SingleOrDefault(o => o.Hashcode.Equals(hashCode));

//it is possible that 2 threads are coming through here and both have obj == null

                if(obj == null)
                {
                    obj = db.Item.Add(new Item
                    {
                        Hashcode = hashCode,
                        State = 0,

                    });
                }

                db.SaveChanges();

                dbContextTransaction.Commit();
            }
            catch(Exception)
            {
                dbContextTransaction.Rollback();
            }
        }
    }
4

1 に答える 1