在 EF MVC5 中更新子 class
Update sub class in EF MVC5
有模特:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int ID { get; set; }
public string Street { get; set; }
}
简化的编辑视图是:
@model ChickCRM.Models.Company
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.AddressId)
@Html.HiddenFor(model => model.Address.ID)
@Html.EditorFor(model => model.Name)
<br />
@Html.EditorFor(model => model.Address.Street)
<br />
<input type="submit" value="Save" />
}
1) 我不知道如何在公司编辑方法中更新地址属性(它只更新公司属性,而不更新街道)。
我的意思是:
[HttpPost]
public ActionResult Edit(Company company)
{
db.Entry(company).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("");
}
2) 我不知道如何使用 sub-属性 Address.Street 的验证包含属性(如果我想使用它的话)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Name,AddressId,Address.Street")] Company company)
...
问题已解决改变子class的状态:db.Entry(company.Address).State = EntityState.Modified;
有模特:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int ID { get; set; }
public string Street { get; set; }
}
简化的编辑视图是:
@model ChickCRM.Models.Company
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.AddressId)
@Html.HiddenFor(model => model.Address.ID)
@Html.EditorFor(model => model.Name)
<br />
@Html.EditorFor(model => model.Address.Street)
<br />
<input type="submit" value="Save" />
}
1) 我不知道如何在公司编辑方法中更新地址属性(它只更新公司属性,而不更新街道)。 我的意思是:
[HttpPost]
public ActionResult Edit(Company company)
{
db.Entry(company).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("");
}
2) 我不知道如何使用 sub-属性 Address.Street 的验证包含属性(如果我想使用它的话)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Name,AddressId,Address.Street")] Company company)
...
问题已解决改变子class的状态:db.Entry(company.Address).State = EntityState.Modified;