实体框架:更新相关的实体 [英] Entity Framework: Update related entities

查看:100
本文介绍了实体框架:更新相关的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:发票和InvoiceDetail

I have two entities: Invoice and InvoiceDetail.

发票有InvoiceDetails成员。

Invoice has an InvoiceDetails member.

当我创建它工作正常。一个obcjet

When I create an obcjet it works as expected.

的框架插入在数据库中的发票和InvoiceDetail行

The framework inserts the Invoice and the InvoiceDetail rows in the database.

$.ajax({
    url: "/Invoices/Index",
    data: JSON.stringify({
        InvoiceDetails: [{
            Description: "1"
        }, {
            Description: "2"
        }]
    }),
    contentType: "application/json",
    type: "POST"
});

    [ActionName("Index")]
    [HttpPost]
    public JsonResult Post(Invoice invoice)
    {
        db.Invoices.AddObject(invoice);
        db.SaveChanges();
        ...

我也想更新发票和相关InvoiceDetails。

I would also like to update Invoice and related InvoiceDetails.

$.ajax({
    url: "/Invoices/Index/1",
    data: JSON.stringify({
        Id: 1,
        InvoiceDetails: [{
            Id: 1,
            Description: "1*"
        }, {
            Id: 2,
            Description: "2*"
        }]
    }),
    contentType: "application/json",
    type: "PUT"
});

    [ActionName("Index")]
    [HttpPut]
    public JsonResult Put(Invoice invoice)
    {
        db.Invoices.Attach(invoice);
        db.ObjectStateManager.ChangeObjectState(invoice, EntityState.Modified);
        db.SaveChanges();
        ...

不过,框架仅更新发票。

But the framework updates only the invoice.

我怎么能同时更新相关的实体?

How can I update also the related entities?

我的模型看起来像这样

编辑:该解决方案
http://michele.berto.li/update-of-an-object-and-related-records-with-backbonejs-and-net-mvc

更新的链接
http://michele.berto.li/update-of-an-object-and-related-records-with-backbone-js-and-net-mvc/

推荐答案

当你调用 ChangeObjectState 你改变单一实体的状态,关系保持不变的状态。所以,如果你只修改现有发票的细节,你可以简单地重复那些细节,并将其设置为修改状态为好。如果你还可以添加或删除的细节将是<一个href=\"http://stackoverflow.com/questions/3635071/update-relationships-when-saving-changes-of-ef4-poco-objects/3635326#3635326\">much更复杂的,你将不得不手动从要求与国家同步数据库中的状态(装发票的细节首次从作为@Hammerstein建议数据库),或使用一些约定来发现哪些细节要删除或添加必须设置状态,而不在数据库中检查它。

When you call ChangeObjectState you are changing state of single entity, relations remain in unchanged state. So if you only modify existing invoice details you can simply iterate those details and set them to modified states as well. If you also can add or remove details it will be much more complicated and you will have to manually sync the state from request with state in database (loading invoice with details first from the database as @Hammerstein suggested) or use some convention to find which details must be set to deleted or added state without checking it in the database.

这篇关于实体框架:更新相关的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆