更新ASP.NET MVC中的导航属性 [英] Update navigation properties in ASP.NET MVC

查看:161
本文介绍了更新ASP.NET MVC中的导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在我之前的帖子中看到我的数据库图: MVC EF - 更新导航属性< a>

You can see my database diagram on my previous post: MVC EF - Update navigation property

我想删除并插入一个帖子的类别。
我收到错误集合已修改;枚举操作可能无法执行。在行

I want to delete and insert categories for one post. I get the error Collection was modified; enumeration operation may not execute. at the row

foreach (PostMapping pm in current_list_category)

这是我的功能:

//
// POST: /BlogPost/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Post post, int[] selectedCategories)
{
   if (ModelState.IsValid)
   {
     List<PostMapping> current_list_category = db.PostMappings.Where(p => p.PostID == post.ID).ToList();
     post.PostMappings = current_list_category;      
     foreach (PostMapping pm in current_list_category)
     {
        int categoryId = pm.CategoryID.Value;
        if (selectedCategories != null)
        {
           if (selectedCategories.Contains(categoryId))
           {
              selectedCategories = selectedCategories.Where(val => val != categoryId).ToArray();
           }
           else
           {
              post.PostMappings.Remove(pm);
              Category category = db.Categories.Where(c => c.ID == categoryId).SingleOrDefault();
              category.PostMappings.Remove(pm);
           }
        }                  
     }
     foreach (var id in selectedCategories)
     {
        Category category = db.Categories.Where(c => c.ID == id).SingleOrDefault();
        PostMapping postMap = new PostMapping();
        postMap.Category = category;
        postMap.Post = post;
        postMap.ID = Guid.NewGuid();
        post.PostMappings.Add(postMap);
        category.PostMappings.Add(postMap);
     }
     db.Entry(post).State = EntityState.Modified;       
     db.SaveChanges();
     return RedirectToAction("Index");
   }
   return View(post);
}

是否有其他方法?

我不再收到错误,但现在我还有另一个问题。

I don't get anymore the error but now I have another problem.

更新前我有这个在数据库中:

Before updating I have this in database:

PostID CategoryID

1 1

1 2

1 3

PostID CategoryID
1 1
1 2
1 3

,但更新后(我想删除类别与ids 1,2,3和添加类别为4)

, but after I update(I want to remove categories with ids 1,2,3 and add category with id 4)

PostID CategoryID

1 NULL

1 NULL

1 NULL

1 4

PostID CategoryID
1 NULL
1 NULL
1 NULL
1 4

为什么?

我尝试过另一种方法,但没有成功:

I tried another approach but with no succes:

.....
Post post2 = db.Posts.Where(p => p.ID == post.ID).SingleOrDefault();
post2.PostMappings.Remove(pm);
Category category = db.Categories.Where(c => c.ID == categoryId).SingleOrDefault();
category.PostMappings.Remove(pm);
 .....

代替:

....
post.PostMappings.Remove(pm);
Category category = db.Categories.Where(c => c.ID == categoryId).SingleOrDefault();
category.PostMappings.Remove(pm);
.....

但是我收到错误: AcceptChanges不能继续因为对象的键值与ObjectStateManager中的另一个对象冲突。确保键值在调用AcceptChanges之前是唯一的。

推荐答案

您在枚举时不能更改集合它
,所以你需要临时收集和枚举它。
这样的东西:

You can't change collection while you enumerating it so you need temporary collection and enumerate over it. something like this:

post.PostMappings = current_list_category;

List<PostMapping> temp = new List<PostMapping>();
temp.AddRange(current_list_category);

foreach (PostMapping pm in temp)
        {
            int categoryId = pm.CategoryID.Value;
            if (selectedCategories != null)
            {
                if (selectedCategories.Contains(categoryId))
                {
                    selectedCategories = selectedCategories.Where(val => val != categoryId).ToArray();
                }
                else
                {

                    post.PostMappings.Remove(pm);
                    Category category = db.Categories.Where(c => c.ID == categoryId).SingleOrDefault();
                    category.PostMappings.Remove(pm);
                }
            }

        }

甚至更好的是,如果您只需要删除几个项目,您可以在单独的列表中收集已删除的项目,然后枚举该列表,并从源列表中删除项目

Or even better especially if you have just few items for remove, you can collect removed items in separate list and then enumerate over that list and remove item from source list

根据发布编辑更改:

您还需要将删除的条目标记为 EntityState.Deleted

you also need to mark your removed entries state as EntityState.Deleted

这篇关于更新ASP.NET MVC中的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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