我刚迁移,代码优先,因此客户模型具有可选地址,并且该地址具有所需客户:
modelBuilder.Entity<Customer>()
.HasOptional(c => c.BillingAddress)
.WithRequired(a => a.Customer);
modelBuilder.Entity<CustomerBillingAddress>()
.HasKey(a => a.CustomerId);
如果我从现在开始创建客户,这非常有用。
在添加地址之前存在的任何客户 - 我无法编辑,添加地址详细信息,并回发到“编辑”,因为我的ModelState无效,并且在billingAddress上存在CustomerId必需错误。
在尝试使用ModelState.IsValid之前,我已尝试测试该值并设置地址ID以匹配客户,但这似乎无效。
我当然可以直接修改数据库/迁移并重新执行或更新我的2个测试客户以获得空白的帐单邮寄地址来解决此问题。
但是......我想知道发生了什么。
此处的相关代码
public class CustomerBillingAddress
{
[ScaffoldColumn(false)]
public long CustomerId { get; set; }
public string Street { get; set; }
[Display(Name = "Street 2")]
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Postal")]
public string PostalCode { get; set; }
public Customer Customer { get; set; }
[ScaffoldColumn(false)]
public string Location => City + ", " + State;
}
“编辑视图”确实包含隐藏字段:
@Html.HiddenFor(model => model.CustomerId)
@Html.HiddenFor(model => model.BillingAddress.CustomerId)
相关的控制人行动:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerId,BillingName, Name,PhysicalAddress, BillingAddress, Active")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
if (customer.PhysicalAddress != null)
{
db.Entry(customer.PhysicalAddress).State = EntityState.Modified;
}
if (customer.BillingAddress != null)
{
db.Entry(customer.BillingAddress).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}