我有以下情況:public class Car { public int ID {get;set} // identity in DB ...}public class Book{ public int ID {get; set;} // identity in DB public int Number {get; set;} .....}由于在數(shù)據(jù)庫和EF模型中這兩個(gè)實(shí)體都不相關(guān),所以我試圖獲取CarID并將其添加到Number字段,所有這些都在一個(gè)DB事務(wù)中一起進(jìn)行,而沒有更新。我知道如何在T-SQL中執(zhí)行此操作: INSERT INTO dbo.Car ()... INSERT INTO dbo.Book(Number) VALUES scope_identity. 以下代碼在C#+ EF(不是CORE)中。public void MyMethod(){ var newCar = newCar(); var newBook = newBook(); myContext.Cars.Add(newCar); myContext.Books.Add(newBook); newBook.Number = newCar.ID; myContext.SaveChanges();}//this example doesn't work, Number is always 0.上面的示例已簡化,可能違反了某些模式,但重點(diǎn)是如何使用EF進(jìn)行此工作。
如何在單個(gè)事務(wù)中重復(fù)使用從實(shí)體框架返回的ID
ibeautiful
2021-05-04 17:14:09