2

I have 2 entity objects "Persons" and "Seminar". Relationship - many to many. A project consist of - EF4.0/STE, WCF and WinForms.

When i try Add Persons To Seminar

 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();

i have exeption -

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.

Please,explain how to fix it Thanks

zs2020
  • 53,766
  • 29
  • 154
  • 219
matelepa
  • 21
  • 1

1 Answers1

0

Could it be the issue that your seminar and persons are from different objectcontext and you are creating new context. You correctly attach the seminar to that context, but you are adding the persons to the newly created context from the old context?

Janne Matikainen
  • 5,061
  • 15
  • 21