uniquekey例外を回避するために、複数のLINQ更新を実行します
-
07-07-2019 - |
質問
ParentRef列とSortIndex列に一意のキーを持つデータベースがあります。
LINQでは、2つのSortIndex値を切り替えます。一度に複数のユーザーが存在できるように、1つのトランザクションでこれを行いたいです。 LINQを使用して、一意のキーに違反しないように値を一度に切り替えるにはどうすればよいですか?
var dc = new MyDataContext();
using (TransactionScope trans = new TransactionScope())
{
var pageToBeMoved = dc.Pages.Where(p => p.ID == id).Single();
var pageToBeSwitched = (from p in dc.Pages
where p.ParentRef == pageToBeMoved.ParentRef
where p.SortIndex > pageToBeMoved.SortIndex
orderby p.SortIndex ascending
select p).First();
int tempSortIndex = pageToBeMoved.SortIndex;
pageToBeMoved.SortIndex = pageToBeSwitched.SortIndex;
pageToBeSwitched.SortIndex = tempSortIndex;
dc.SubmitChanges();
trans.Complete();
}
解決
一意のキー値を切り替えるには、切り替え中に3番目の一時的な値を使用する必要があると思います。
- 新しい値を作成
- page2.SortIndexを新しい値に設定
- page1.SortIndexを古いpage2.SortIndexに設定
- page2.SortIndexを古いpage1.SortIndexに設定
...それ以外の場合、切り替え中に一意のキー違反が発生する可能性があります。
これらの線に沿ったもの:
var dc = new MyDataContext();
using (TransactionScope trans = new TransactionScope())
{
var pageToBeMoved = dc.Pages.Where(p => p.ID == id).Single();
var pageToBeSwitched = (from p in dc.Pages
where p.ParentRef == pageToBeMoved.ParentRef
where p.SortIndex > pageToBeMoved.SortIndex
orderby p.SortIndex ascending
select p).First();
int oldMSortIndex = pageToBeMoved.SortIndex;
int oldSSortIndex = pageToBeSwitched.SortIndex;
// note: here you need to use some value that you know will not already
// be in the table ... maybe a max + 1 or something like that
int tempSortIndex = someunusedvalue;
pageToBeMoved.SortIndex = tempSortIndex;
dc.SubmitChanges();
pageToBeSwitched.SortIndex = oldMSortIndex;
dc.SubmitChanges();
pageToBeMoved.SortIndex = oldSSortIndex;
dc.SubmitChanges();
}
所属していません StackOverflow