c# - 编辑多对多关联的操作

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

我正在为网站上的新闻制作标签。首先使用实体​​框架代码。 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。创建和删除操作工作正常。这是我尝试过的方法,它正确更新了所有帖子字段,但忽略了标签。

[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 指出方向。

最佳答案

我的建议:

[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
}

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

关于c# - 编辑多对多关联的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9051809/

相关文章:

c# - 在 html mvc C# 中访问多个 ViewModel

asp.net-mvc - 从 MVC 应用程序中的 ClaimsPrincipal 获取 bootStrapContext token

c# - db.SaveChanges() 期间出现 "Invalid Object Name"错误( Entity Framework /MVC)

c# - 在非托管 DLL 中存储 "managed"上下文参数

c# - StackExchange.Redis 异步调用比同步调用慢

c# - 项目部署

asp.net-mvc - 传递到 Html.ActionLink 时序列化模型上的 IList 属性

c# - 使用 IEnumerable.Select 过滤记录

c# - 属性id是对象关键信息的一部分,不可修改

c# - StringBuilder 编码导致 PInvokeStackImbalance 异常