我有一個與製造商有外鍵關係的產品實體。我想讓用戶添加新產品是否想要設置製造商。Modelbinder創建一個對外關係不必要..如何解決?
在我創建視圖我有,
<%= Html.LabelFor(p => p.Manufacturer.Name) %>
<%= Html.EditorFor(p => p.Manufacturer.Name) %>
在創建行動,
public ActionResult Create(Product product) {
if (product.Manufacturer != null &&
!String.IsNullOrEmpty(produnt.Manufacturer.Name) &&
!String.IsNullOrWhiteSpace(produnt.Manufacturer.Name)) {
Manufacturer manufacturer = _session.Single<Manufacturer>(m => m.Name.Equals(produnt.Manufacturer.Name));
if (manufacturer == null) {
_session.Add(product.Manufacturer);
}
product.Manufacturer = manufacturer;
}
_session.Add(product);
}
在廠家表我只是有編號和名稱列。該名稱被設置爲NOT NULL。每個產品都有ManufacturerID,可以是NULL。我已從Manufacturer.ID添加FK關係< => Product.ManufacturerID。
我還使用DefaultValue數據註釋和模型元數據將Product.ManufacturerID的默認值設置爲null。
當我在創建產品時指定某些製造商時,此工作正常。但是,當我將其留空時,會爲數據庫中的Product.ManufacturerID分配一個ID,但不會使用該ID創建制造商。調試器顯示Product.Manufacturer.Name爲null,但由於某種原因Product.Manufacturer.ID和Product.ManufacturerID被設置爲0(非空)。如何在沒有指定製造商的情況下使Product.ManufacturerID爲空?
難道是一個更好的主意,脫離製造商的實體,具有操作這個樣子的,
public ActionResult Create(Product product, Manufacturer manufacturer) {
// ...
}
我猜依靠模型綁定太多是不是一個好主意。