ASP MVC如何使用集合字段更新数据库条目 [英] ASP MVC How to update DB entry with collections field

查看:97
本文介绍了ASP MVC如何使用集合字段更新数据库条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的示例,如何正确保存更新的模型?我担心一些疯狂的东西,例如自定义模型绑定等.我想用优雅的方式解决这个问题.

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.

模型

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" />

这是创建Actio n

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

推荐答案

尝试一下...评论中的解释

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

这篇关于ASP MVC如何使用集合字段更新数据库条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆