Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Update related entities

I have two entities: Invoice and InvoiceDetail.

Invoice has an InvoiceDetails member.

When I create an obcjet it works as expected.

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

But the framework updates only the invoice.

How can I update also the related entities?

My model looks like this

enter image description here

EDIT: The solution http://michele.berto.li/update-of-an-object-and-related-records-with-backbonejs-and-net-mvc

UPDATED LINK http://michele.berto.li/update-of-an-object-and-related-records-with-backbone-js-and-net-mvc/

like image 926
user758977 Avatar asked Mar 16 '26 01:03

user758977


1 Answers

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.

like image 181
Ladislav Mrnka Avatar answered Mar 17 '26 21:03

Ladislav Mrnka