问题
For the attached example below, how can i properly save my updated model? I am afraid of some crazy stuff like custom model binding,etc. and I want to solve this with elegance.
Model
public class Artist {
public int ArtistId { get; set; }
public string ArtistName { get; set; }
public virtual ICollection<Album> ArtistAlbums { get; set; }
}
public class Album {
public int AlbumId { get; set; }
public string AlbumName { get; set; }
}
Snippet from Create View
<input type="text" name="ArtistAlbums" />
<input type="text" name="ArtistAlbums" />
Here is the Create Action
public ActionResult Create(Artist newArtist, IEnumerable<string> ArtistAlbums) {
foreach (var album in ArtistAlbums) {
newArtist.ArtistAlbums.Add(new Album { AlbumName = album });
}
db.Entry(newArtist).State = EntityState.Added;
db.SaveChanges();
return RedirectToAction("Index");
}
Here is my piece of Edit View
@foreach (var album in Model.ArtistAlbums) {
<div>@album.AlbumName</div>
<input type="text" name="ArtistAlbums" />
}
Here is my Edit Action
[HttpPost]
public ActionResult Edit(Artist artist, IEnumerable<string> ArtistAlbums) {
foreach (var album in ArtistAlbums) {
artist.ArtistAlbums.Add(new Album { AlbumName = album });
}
// An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
//db.Entry(artist).State = EntityState.Modified;
// this one update my Artist entry, but not my Albums for this entry.
// var oldArtist = db.Artists.Find(artist.ArtistId);
// db.Entry(oldArtist).CurrentValues.SetValues(artist);
db.SaveChanges();
return RedirectToAction("Index");
}
回答1:
In your edit action:
ArtistAlbums.ToList().ForEach(album=>artist.ArtistAlbums.Add(new Album { AlbumName = album }));
db.Artists.Attach(artist);
db.ObjectStateManager.ChangeObjectState(artist,EntityState.Modified);
db.SaveChanges();
回答2:
Try this... Explanation in comment
[HttpPost]
public ActionResult Edit(Artist artist, IEnumerable<string> ArtistAlbums)
{
// First detach the object with same key
Artist tbd = db.Artists.Find(artist.Id);
((IObjectContextAdapter)db).ObjectContext.Detach(tbd);
foreach (var album in ArtistAlbums)
{
artist.ArtistAlbums.Add(new Album { AlbumName = album });
}
// The above error should not occur now.
db.Entry(artist).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
来源:https://stackoverflow.com/questions/12020518/asp-mvc-how-to-update-db-entry-with-collections-field