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

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

问题描述

我有两个实体:发票和发票详细信息。

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();
        ...

我也想更新发票和相关的发票详细信息。 >

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();
        ...

但框架仅更新发票。

如何更新相关实体?

我的模型看起来像这样

编辑:解决方案
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 您正在更改单一权限的状态y,关系保持不变。因此,如果您只修改现有的发票明细,您可以简单地迭代这些细节,并将其设置为修改状态。如果您也可以添加或删除详细信息,那将是更复杂的,您将不得不手动将状态从请求中同步到数据库中(状态为加载发票,首先从@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天全站免登陆