我建立了一個多對多的關係,代碼優先有效,為 API 生成了數千條虛假記錄。現在我試圖在該關係的一側保存一條新記錄,只給定另一側的 id,因為客戶端正在傳遞一個 int id 數組。
我發現了很多關於保存多對多的問題和答案的問題,但沒有一個專門針對僅使用外鍵列表進行保存的問題。也許我只是使用了錯誤的術語?
我可以預先獲取這些 id 的所有記錄,但是等待數據庫查詢,將這些實體分配給新實體,然後再次進入數據庫進行保存,這似乎很繁重,而我真正需要的是建立與我已經擁有的身份的關係。
對於單個關係,我只需將外鍵添加為單獨的屬性並設置它而不是外部實體本身:
public int? CarId { get; set; }
[ForeignKey("CarId")]
public CarModel? Car { get; set; }
多對多可能有類似的範例嗎?
實體設置:
public class ClownModel {
public int Id { get; set; }
public List<CarModel> Cars { get; set; }
}
public class CarModel {
public int Id { get; set; }
public List<ClownModel> Clowns { get; set; }
}
數據庫上下文 OnModelCreating:
builder.Entity<ClownModel>()
.HasMany(x => x.Cars)
.WithMan(x => x.Clows);
您可以使用“存根實體”將現有汽車添加到新的或現有的小丑,而無需獲取汽車。例如
var newClown = new Clown();
var car = new Car() { Id = carId };
db.Entry(car).State = EntityState.Unchanged;
newClown.Cars.Add(car);
db.Set<Clown>().Add(newClown);
db.SaveChanges();
或者在模型中包含鏈接實體,無需添加 DbSet 屬性或更改多對多導航屬性即可執行此操作。
例如
builder.Entity<Clown>()
.HasMany(x => x.Cars)
.WithMany(x => x.Clowns)
.UsingEntity<ClownCar>(
c => c.HasOne(x => x.Car)
.WithMany()
.HasForeignKey(x => x.CarId),
c => c.HasOne(c => c.Clown)
.WithMany()
.HasForeignKey(c => c.ClownId)
);
然後
var newClown = new Clown();
var clownCar = new ClownCar();
clownCar.CarId = carId;
clownCar.Clown = newClown;
db.Set<ClownCar>().Add(clownCar);
db.SaveChanges();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句