MVC MultiSelect EF多对多编辑 [英] MVC MultiSelect EF many to many Edit

查看:136
本文介绍了MVC MultiSelect EF多对多编辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,保存一个多选框,它工作正常,但是当我尝试编辑一个记录我得到以下错误。添加其他所选标签的最佳方式是什么?在编辑时删除任何未选择的标签?

Below is my code that saves a multi select box, it works fine, but when i try to edit a record i get the error below. Whats the best way to add just the additional selected tags, and to remove any unselected tags when editing?


失败是因为另一个相同的实体类型已经具有相同的主键值。当使用附加方法或将实体的状态设置为不变或修改时,如果图中的任何实体具有冲突的键值,则可能会发生这种情况。这可能是因为一些实体是新的,并且尚未接收到数据库生成的键值。在这种情况下,使用添加方法或添加实体状态来跟踪图形,然后根据需要将非新实体的状态设置为不变或修改。

failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.



public class Post
{     
    public Guid PostId { get; set; }     
    public string Name { get; set; }       
    public virtual ICollection<Tag> Tags { get; set; }
}

  public class Tag
{
    public int TagId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Create()
    {
        var tags = new List<Tag>()
            {
                new Tag() { TagId = 1, Name = "Planes", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Cars", Posts = new Collection<Post>() },
                new Tag() { TagId = 2, Name = "Boats", Posts = new Collection<Post>() }
            };

        ViewBag.MultiSelectTags = new MultiSelectList(tags, "TagId", "Name");

        return View();
    }

    [HttpPost]
    public ActionResult Create(Post post, int[] tags) 
    {

           foreach (var tag in tags)
            {
                Tag t = db.ThemeFeatures.Where(t => t.TagId== tag).First();
                themedetails.ThemeFeatures.Add(t);   
            }

         context.SaveChanges();

        return RedirectToAction("Create");
    }

}

创建视图


@model MvcApplication1.Models.Post

@model MvcApplication1.Models.Post

@using(Html.BeginForm(Create,Home,FormMethod.Post)){
名称
@ Html.TextBoxFor(model => model.Name)

@using (Html.BeginForm("Create", "Home", FormMethod.Post)) { Name @Html.TextBoxFor(model => model.Name)

<label>Tags For Post</label>
@Html.ListBox("Tags", (MultiSelectList)ViewBag.MultiSelectTags)

<input type="submit" value="Submit Post"/> }



推荐答案

要做的是确保您添加子实体的实体附加到对象上下文。最简单的方法是使用您的视图中的POSTed ID获取一个新的上下文对象。

What you want to do is make sure the entity you're adding child-entities to is attached to the object context. The easiest way to do this is just get a fresh context object using the POSTed ID from your view.

你不会保存任何令人担忧的东西与对象之间的区别有。最简单的方法是简单地清除其子集的对象,并添加POST中返回的所有内容。

You won't save anything worrying about getting the difference of what the object has versus what the object should have. The easiest way to handle that is to simply clear the object of its child collection and add everything that came back from the POST.

[HttpPost]
public ActionResult Create(Post post, int[] tags) 
{
     ...
     var freshPost = db.Posts.Find(post.ID);
     freshPost.Tags.Clear();
     foreach (var tag in tags)
     {
         Tag t = db.ThemeFeatures.Find(tag);
         freshPost.Tags.Add(t);
     }

     context.SaveChanges();
}

这篇关于MVC MultiSelect EF多对多编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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