更新EF MVC5中的子类

时间:2015-02-09 01:00:27

标签: asp.net-mvc entity-framework edit

有模特:

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)我不知道如何在公司编辑方法中更新地址属性(它只是更新公司的属性,而不是Street)。 我的意思是:

    [HttpPost]
    public ActionResult Edit(Company company)
    {
            db.Entry(company).State = EntityState.Modified;
            db.SaveChanges();

            return RedirectToAction("");
    }

2)我不知道如何使用子属性Address.Street的验证Include属性(如果我想使用它)

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,Name,AddressId,Address.Street")] Company company)
...

1 个答案:

答案 0 :(得分:0)

问题解决了更改子类的状态:db.Entry(company.Address).State = EntityState.Modified;