public class Car {
public string SomeProperty { get; set; }
public Manufacturer Manufacturer { get; set; }
public IList<Color> Colors { get; set; }
}
public class Manufacturer {
public int Id { get; set; }
public string Name { get; set; }
}
public class Color {
public int Id { get; set; }
public string Name { get; set; }
}
我已經有了充滿顏色和製造商的表格。當我創建一輛新車時,我希望能夠從.net MVC中爲它分配一個顏色和製造商。EF - 使用鏈接的現有實體創建重複的新實體
當我救我的新車
context.Cars.Add(car);
新車創建(偉大的),但一個新的顏色和製造商也創造了即使這些對象已經有一個標識和名稱組相匹配的內容在數據庫中。
我看到的兩種解決方案是爲汽車編寫自定義保存方法,並告訴上下文製造商和顏色未更改。
context.Cars.Add(car);
context.Entry(car.Manufacturer).State = EntityState.Unchanged;
foreach (Color color in car.Colors)
context.Entry(car.Color).State = EntityState.Unchanged;
另外,加載從EF製造商和顏色,然後將它們聯繫起來,而不是使用MVC綁定對象的車。
car.Manufacturer = carRepository.GetManufacturer(car.Manufacturer.Id);
car.Colors = carRepository.GetColorsById(car.Colors);
我對這兩個解決方案都不感到興奮,因爲這個例子非常微不足道,但是我的真實情況要複雜得多。我真的不想爲每個保存的對象詳細介紹EF。我有很多複雜的對象圖來保存,這似乎很容易出錯。
有沒有一種方法可以讓EF的表現更像NHibernate,你可以給它一些已經分配了ID的東西,它會假定沒有你的介入它已經存在了?
編輯 - 澄清的問題顯示現有實體的集合以及多對一的關係。
謝謝,這是一個關於這種類型的關係的好點。 如果我有一個IList而不是現有的實體添加到此? –
Plessiez
@Plessiez:在這種情況下,你堅持從數據庫中加載它們。你仍然可以在一個鏡頭中執行'(context.Colors.Where(x => listOfColorIds.Contains(x.Id))' –