Führen Sie mehrere LINQ Updates UniqueKey Ausnahme zu vermeiden
-
07-07-2019 - |
Frage
Ich habe eine Datenbank mit einem eindeutigen Schlüssel auf denen die Spalten ParentRef und SortIndex.
In LINQ, ich möchte zwei SortIndex Werten wechseln. Ich möchte dies in einer Transaktion zu tun, so dass es auf einmal mehrere Benutzer sein kann. Wie kann ich mit LINQ, um die Werte in einem Rutsch wechseln, so dass meine Eindeutiger Schlüssel nicht verletzt wird werden?
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();
}
Lösung
Ich denke, dass eindeutige Schlüsselwerte zu wechseln, könnte man einen dritten temporären Wert während der Schalter verwenden müssen, das heißt:
- Erstellen neuer Wert
- set page2.SortIndex auf den neuen Wert
- set page1.SortIndex zu alt page2.SortIndex
- set page2.SortIndex zu alt page1.SortIndex
... sonst sind Sie wahrscheinlich eine eindeutige Schlüssel Verletzung während des Umschaltens zu treffen.
Etwas in diese Richtung:
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();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow