自我跟踪实体SaveChanges()在多对多关系中添加实体时出现异常

时间:2012-09-07 07:31:02

标签: c# wcf entity-framework entity-framework-4 self-tracking-entities

我有2个实体对象“人物”和“研讨会”。关系 - 多对多。一个项目包括 - EF4.0 / STE,WCF和WinForms。

当我尝试添加人员到研讨会时

 public void AddPersonsToSeminar(Seminar seminar, List<Person> persons)
        {
            using (T3EntitiesConn context = new T3EntitiesConn())
            {
                if (seminar != null)
                {
                    context.Seminar.Attach(seminar);

                    foreach (Person person in persons)
                    {
                        if (!seminar.Person.Any(p => p.ID == person.ID))
                        {
                            seminar.Person.Add(person);
                            context.Seminar.ApplyChanges(seminar);
                        }
                    }
                    context.SaveChanges();

我有例外 -

The property 'ID' is part of the object's key and cannot be changed. Changes to key properties can only be made when the object is not being tracked or is in the Added state.

请解释如何修复它 感谢

1 个答案:

答案 0 :(得分:0)

问题是您的研讨会和人员来自不同的对象上下文并且您正在创建新的上下文。您是否正确地将研讨会附加到该上下文,但是您是将这些人员添加到旧上下文中新创建的上下文中?