以下の添付の例では、更新されたモデルを適切に保存するにはどうすればよいですか? カスタムモデルバインディングなどのクレイジーなものが怖いです。これを優雅に解決したいのです。
モデル
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; }
}
ビューの作成からのスニペット
<input type="text" name="ArtistAlbums" />
<input type="text" name="ArtistAlbums" />
作成アクションは次のとおりです。
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");
}
これが編集ビューの私の作品です
@foreach (var album in Model.ArtistAlbums) {
<div>@album.AlbumName</div>
<input type="text" name="ArtistAlbums" />
}
これが私の編集アクションです
[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");
}