问题
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/
回答1:
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.
回答2:
I've not worked with Attach much, normally I query the database, update the record and ave changes. But I believe the invoice you're attaching doesn't have the same association with the invoice detail. You'll need to pull that record out, update it and then save changes.
来源:https://stackoverflow.com/questions/8615633/entity-framework-update-related-entities