Best way to transfer an Entity Framework object over the web and back via JSON Best way to transfer an Entity Framework object over the web and back via JSON json json

Best way to transfer an Entity Framework object over the web and back via JSON


or you could use AutoMapper to map those fields for you, so you'd just add one extra line to your example.


Why not just use the UpdateModel or TryUpdateModel controller methods instead? It works really well with EF and you can even explicitly set the included property list.

The id parameter will auto-map via the MVC framework to the hidden field on your form specifying the id.

public void Update(int id, FormCollection collection){    using (var db = new BandSitesMasterEntities())    {        var albumToUpdate = db.Album.First(x => x.ID == id);        //use UpdateModel to update object, or even TryUpdateModel        UpdateModel(albumToUpdate, new string[] { "AlbumTitle", "Description", "ReleaseYear", "ImageURL", "OtherURL" });        db.SaveChanges();    }}


This became much easier for us in EF 4.0. This is what we did in EF 3.5:

public static void AttachAsModified(this ObjectContext objectContext, string setName, object entity,                                    IEnumerable<String> modifiedFields){    objectContext.AttachTo(setName, entity);    ObjectStateEntry stateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);    foreach (String field in modifiedFields)    {        stateEntry.SetModifiedProperty(field);    }}

And then:

using (var db = new BandSitesMasterEntities()){    db.AttachAsModified("Album", album, new string[] { "AlbumTitle", "Description", "ReleaseYear", "ImageURL", "OtherURL" })    db.SaveChanges();}

It becomes more complicated if you have foreign key constraints, but it looks like you don't.