c# - ASP.Net MVC。如何使用 Entity Framework 自动持久化关系数据?

标签 c# asp.net asp.net-mvc entity-framework ef-code-first

这是 POCO 代码第一类:

class Contact{
    [Key]
    public int Id {get; set;}
    public string name {get; set;}
    public ICollection<Phone> phones{get; set;}
}

class Phone{
    [Key]
    public int id {get;set;}
    public string phone_type {get; set;}
    public string phone_number {get; set;}
    public Contact contact { get; set; }
}

我想把它持久化在数据库上。

这是 Controller :

绑定(bind)的“contact”实例确实包含一个 Contact with a List phones 和很多电话。

public ActionResult Edit([Bind()] Contact contact) {
    if (ModelState.IsValid)
    {
        db.Entry(contact).State = System.Data.Entity.EntityState.Modified;
        db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(contact);
}

但此代码仅将 Contact 实例保存在数据库中。 Phones 表仍然是空的。

是否有任何配置可以自动将相关的“电话”数据持久化到数据库中,还是必须手动编码?

对于那些感兴趣的人, View 是这样的(简化):

@model SGD.Models.Contact
Name:    @Html.EditorFor(model => model.name)
Phones: <div id="phones"></div>

#phones div 中填充了带有增量索引的部分内容。

<input name="phones[@index].id" type="hidden" />
<input name="phones[@index].phone_type" />
<input name="phones[@index].phone_number" />

最佳答案

现在我正在阅读,如果您只是将根实体中的 State 更改为 Modified,则相关实体不会更改其状态 (reference):

Note that if the entity being attached has references to other entities that are not yet tracked, then these new entities will attached to the context in the Unchanged state—they will not automatically be made Modified. If you have multiple entities that need to be marked Modified you should set the state for each of these entities individually.

尝试使用 TryUpdateModel .我不完全确定它是否会更新相关实体,但如果您的模型绑定(bind)了相关实体,它应该会更新。

var contact= db.Contacts.Include(c=>c.Addresses).FirstOrDefault(c=>c.Id==contact.Id);
TryUpdateModel(contact);

在这种情况下,我总是使用 ViewModel,稍后我使用 Automapper 将其映射到我的实体之一。

还有一个第三方库 ( GraphDiff ) 允许您将整个分离的模型/实体,以及子实体和列表保存到数据库中,而无需编写代码来执行此操作。

关于c# - ASP.Net MVC。如何使用 Entity Framework 自动持久化关系数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527273/

相关文章:

asp.net-mvc - asp.net MVC-3 视频教程?

c# - 使用 C# 登录 JIRA Rest API

c# - 为什么 typeof(Foo) 会返回 null?

c# - IdentityModel 中 TokenClient 的问题

c# - 从 yahoo 凭据导入 yahoo 联系人

c# - CSS 类不能应用于 ASPX C# View 引擎上的 EditorFor

c# - Nhibernate - 将通用 IList 对象映射到单个 DB 列中以逗号分隔的键列表

asp.net - 无法加载类型 'System.Web.Optimization.StyleBundle'

c# - 如何分析 ASP.NET MVC 应用程序中请求的性能?

c# - 我可以在.net MVC 中使用FromBody 和FromUri 吗?