أداء متعددة LINQ التحديثات لتجنب uniquekey استثناء
-
07-07-2019 - |
سؤال
لدي قاعدة بيانات مع مفتاح فريد على الأعمدة ParentRef و SortIndex.
في LINQ, أريد أن التبديل اثنين SortIndex القيم.أريد أن أفعل هذا في معاملة واحدة حتى يمكن أن يكون هناك العديد من المستخدمين في آن واحد.كيف أنا مع 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();
}
المحلول
أعتقد أن التبديل مفتاح فريد القيم ، قد تحتاج إلى استخدام ثلث قيمة مؤقتة أثناء التبديل ، وهذا هو:
- إنشاء قيمة جديدة
- مجموعة 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