【问题标题】:Edit action for many-to-many association编辑多对多关联的操作
【发布时间】:2012-02-21 12:50:34
【问题描述】:

我正在为网站上的新闻制作标签。首先使用实体​​框架代码。 PostTag 关联表(PostId + TagId)是自动生成的。 这是我的模型:

public class Post
{
    public int Id { get; set; }
    //...
    public virtual ICollection<Tag> Tags { get; set; } 
}

public class Tag
{
    public int Id { get; set; }
    //...
    public virtual ICollection<Post> Posts { get; set; } 
}

问题在于为我的管理面板实现 Post Editor Action。创建和删除操作工作正常。这是我尝试过的,它正确更新了所有 Post 字段,但忽略了标签。

[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
if (ModelState.IsValid)
{
    post.Tags = new List<Tag> { };
    if (TagId != null)
        foreach (int f in TagId)
            post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
    db.Entry(post).State = EntityState.Modified;  // Doesnt update tags
    db.SaveChanges();
    return RedirectToAction("Index");
}
//...

解决方案

[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] TagId)
{
    if (ModelState.IsValid)
    {
        Post postAttached = db.Posts.Where(x => x.Id == post.Id).First();
        post.Tags = postAttached.Tags;
        post.Tags.Clear();                
        if (TagId != null)
            foreach (int f in TagId)
                post.Tags.Add(db.Tags.Where(x => x.Id == f).First());
        db.Entry(postAttached).CurrentValues.SetValues(post);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

感谢 gdoron 指点方向。

【问题讨论】:

  • 我不熟悉Entity Framework,但在NHibernate 中,您必须将实体附加到会话,以便跟踪更改。我认为这是你的问题。您从页面获得的 Post 已分离。我说的对吗?
  • 您是否检查过您的数据库并确保已创建关系?
  • gdoron,我不认为是这种情况。你说的超然是什么意思? KMan,是的,我检查了数据库,一切都很好,并且以同样的方式制作的后期创建动作完美无缺。
  • 这个Post 没有被跟踪分离。您必须通过它的 Id\Code 加载帖子并更改此跟踪的实体值。

标签: c# asp.net-mvc entity-framework many-to-many


【解决方案1】:

我的建议:

[HttpPost, ValidateInput(false)]
public ActionResult Edit(Post post, int[] tagIds)
{
    if (ModelState.IsValid)
    {            
        post.Tags = db.Tags.Where(tag => tagIds.Contains(tag.Id));
        db.Entry(post).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    // some code here
}

我没有测试,你能帮我们确认一下吗?

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多