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

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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With