0

以下の添付の例では、更新されたモデルを適切に保存するにはどうすればよいですか? カスタムモデルバインディングなどのクレイジーなものが怖いです。これを優雅に解決したいのです。

モデル

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");
}
4

2 に答える 2

0

これを試してください...コメントでの説明

[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");
}
于 2014-03-08T13:47:03.307 に答える
0

編集アクションで:

ArtistAlbums.ToList().ForEach(album=>artist.ArtistAlbums.Add(new Album { AlbumName = album }));
    db.Artists.Attach(artist);
    db.ObjectStateManager.ChangeObjectState(artist,EntityState.Modified);
    db.SaveChanges();
于 2012-08-19T15:57:14.050 に答える