Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write a generic WebAPI Put method against Entity Framework that works with child lists?
    primarykey
    data
    text
    <p>I am tinkering with WebAPI to create a generic implementation for entity framework. I am able to implement most of the methods just fine, but am finding PUT to be tricky in non-trivial cases. The implementation most commonly found online works for simple entities:</p> <pre><code> [HttpPut] [ActionName("Endpoint")] public virtual T Put(T entity) { var db = GetDbContext(); var entry = db.Entry(entity); entry.State = EntityState.Modified; var set = db.Set&lt;T&gt;(); set.Attach(entity); db.SaveChanges(); return entity; } </code></pre> <p>...but does not delete or update child lists:</p> <pre><code> public class Invoice { ... public virtual InvoiceLineItem {get; set;} //Attach method doesn't address these } </code></pre> <p>In an MVC Controller, you could simply use "UpdateModel" and it would add/update/delete children as needed, however that method is not available on ApiController. I understand that some code would be necessary to get the original item from the database, and that it would need to use Include to get the child lists, but can't quite figure out the best way to replicate UpdateModel's functionality:</p> <pre><code> [HttpPut] [ActionName("Endpoint")] public virtual T Put(T entity) { var db = GetDbContext(); var original = GetOriginalFor(entity); //TODO: Something similar to UpdateModel(original), such as UpdateModel(original, entity); db.SaveChanges(); return original; } </code></pre> <p>How can I implement UpdateModel OR somehow implement Put in such a way that it will handle child lists?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload