在EF中更新收藏 [英] Updating collection in EF

查看:32
本文介绍了在EF中更新收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常如何在EF中更新收藏集?想象一下,我们有一个带有相对表的模型 M1 ,EF表示为 ICollection< F1> ,并且可以编写类似 Entities.M1.F1.Where(...).

How you usually update collection in EF? Imagine, that we have some model M1 with relative table, which EF presents as ICollection<F1> and can write code like Entities.M1.F1.Where(...).

public partial class M1
    {
        public M1()
        {
            this.F1 = new HashSet<F1>();
        }
        public int Id { get; set; }
        public virtual ICollection<F1> F1 { get; set; }
    }

那么,用另一种更新相对于 F1 的相对集合的最佳方法是什么?
简单赋值 Entities.M1.F1 = newData; 会导致数据重复,并通过清除 Entities.M1.F1.Clear();进行赋值;Entities.M1.F1 = newData; 产生以下异常:

So, what is the best way to update relative collection of F1 with another one?
Simple assignment Entities.M1.F1 = newData; results data duplication, assignment with clearing Entities.M1.F1.Clear(); Entities.M1.F1 = newData; produces following exception:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

带有InnerException

with the InnerException

{"A relationship from the 'FK_F1_M1' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'F1' must also in the 'Deleted' state."}

推荐答案

当前,没有直接的方法可以更新EF中的集合.您需要遍历每个参考对象并在集合中添加/删除.在以下示例中为f.x

currently there is no straightforward way to update collection in EF. you need to go through each reference object and add/remove in collection. f.x in this example below

 var selectedCoursesHS = new HashSet<string>(selectedCourses);
            var instructorCourses = new HashSet<int>
                (instructor.Courses.Select(c => c.CourseID));

            foreach (var course in schoolContext.Courses)
            {
                if (selectedCoursesHS.Contains(course.CourseID.ToString()))
                {
                    if (!instructorCourses.Contains(course.CourseID))
                    {
                        instructor.Courses.Add(course);
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.CourseID))
                    {
                        instructor.Courses.Remove(course);
                    }
                }
            }

更新此内容后,您需要针对上下文修改状态,然后执行savechanges()

once you update this you need to make a state as modified for your context and then do savechanges()

希望得到帮助!

这篇关于在EF中更新收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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