Need advice regarding handling updating many-to-many relationships in Entity Framework

52 views Asked by At

WHAT I HAVE:

Visual Basic 2015, Entity Framework (DBContext), WinForms

MY PROBLEM:

I'm writing a VB 2015 program using EF (Model-First, since I'm starting from scratch), and some of my entities have many-to-many relationships. I read that in order to add or remove a relationship between an instance of Entity1 and an instance of Entity2, one has to do the following:

' get entities

Dim e1 As Entity1 = query getting an instance of Entity1   'Navigation property: e1.Entity2Collection*

Dim e2 As Entity2 = query getting an instance of Entity2   'Navigation property: e2.Entity1Colection*

' populate collection

dbc.Entry(e1).Collection(Function(e) e.Entity2Collection).Load()   'lambda overload

or

dbc.Entry(e1).Collection("Entity2Collection").Load()   ' string overload

' perform update

e1.Entity2Collection.Add(e2)
dbc.SaveChanges()

or

e1.Entity2Colection.Remove(e2)
dbc.SaveChanges()

The Entry/Collection/Load statement is important because the relationship won't be properly added/removed unless the collection is populated (another way is to use the Include method in the original query).

But here's where I'm unsure what to do:

Suppose Entity1 has a many-to-many relationship with each of 2 or more other entities--for instance,

Entity 1 is many-to-many with Entity2,

Entity1 is many-to-many with Entity3, and

Entity1 is many-to-many with Entity4

Do I need to also do:

dbc.Entry(e1).Collection(Function(e) e.Entity3Collection).Load()

dbc.Entry(e1).Collection(Function(e) e.Entity4Collection).Load()

before doing the Add or Remove in order for the above update to work properly?

0

There are 0 answers