0

I have these models:

public class GroupSetCollection {
    int Id { get; set; }
    string Name { get; set; }
    List<GroupSet> GroupSets { get; set; }
}

public class GroupSet {
    int Id { get; set; }
    string Name { get; set; }
    List<Group> Groups{ get; set; } 
}

Whenever I update the GroupSetCollection all the properties are updated except for the GroupSets. When I manually call the update on the GroupSet it gives me the following error.

Attaching an entity of type 'GroupSet' failed because another entity of the >same type already has the same primary key value for child.`

Below is the method I'm using to update the entities. It fails at the GroupSet update and works fine on the GroupSetCollection update.

public void UpdateGroupSetCollection(GroupSetVM groupSetCollection)
        {
            _GroupSetCollectionService.Update(VMToEntity(groupSetCollection));
            _GroupSet.Update(groupSetCollection.GroupSets);

        }
Jack Tyler
  • 479
  • 4
  • 17
  • 1
    If `List GroupSets` are related with the `GroupSetCollection`, it isn't necessary update the entities individualy. So, when `GroupSetCollection` is updated, its entities related are also updated. Maybe adding `public virtual List GroupSets {get; set;}` will fix the problem. – JPocoata Sep 04 '18 at 16:26
  • Possible duplicate: https://stackoverflow.com/questions/27176014/how-to-add-update-child-entities-when-updating-a-parent-entity-in-ef – Gauravsa Sep 05 '18 at 01:12
  • @JesusPocoata That's it! They weren't set to virtual that was my issue. Thanks for your help. – Jack Tyler Sep 05 '18 at 09:56

2 Answers2

1

There are many ways to load related entities, one of them is add the word virtual to the related entity.

So, you final class will be:

public class GroupSetCollection {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<GroupSet> GroupSets { get; set; }
}

You could also read about Loading Related Entities from the official documentation.

JPocoata
  • 558
  • 1
  • 10
  • 24
0

Thanks to @JesusPocoata for helping my figure out the issue.

I hadn't set the List<GroupSet> to virtual once that was done it worked perfectly.

Jack Tyler
  • 479
  • 4
  • 17