我有一个与制造商有外键关系的产品实体。我想让用户添加新产品是否想要设置制造商。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) {
// ...
}
我猜依靠模型绑定太多是不是一个好主意。