我有一张这样的桌子
UserPageId (Primary Key) int
UserId (user Foreign Key) int
PageId (page Foreign Key) int
整个场景是为了防止用户多次添加一个页面,根据每个用户可以和几个人一起使用,我们可能有并发用户
首先我想通过隔离级别 Serializable 来解决这个问题,但它以死锁结束
我的职能是:
public void Add(int PageId,int UserId)
{
using (TransactionScope scope = newTransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
{
using (entities EFmodel = new entities())
{
EFmodel.Connection.Open();
EFmodel._UserId = UserId;
if (!Pages.Exists(EFmodel, PageId))
Pages.Add(EFmodel, PageId);
else
ERModel.AddModelError("", "you have already added this page");
EFmodel.SaveChanges();
}
scope.Complete();
}
return ERModel;
}
页面。存在:
public bool Exists(entities EFmodel, int PageId)
{
int ctn = EFmodel.UserPages.Count(x => x.PageId == PageId && x.UserId == EFmodel._UserId);
if(ctn!=0)
return true;
return false;
}
页面。添加:
public static void Add(entities EFmodel,int PageId)
{
UserPage userpage = new UserPage()
{
UserId = EFmodel._UserId,
PageId = PageId,
UserPageId = 0
};
EFmodel.UserPages.AddObject(userpage);
}