locked
How do I handle an entity which has many-to-many relationships with more than one other entity? RRS feed

  • General discussion

  • 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 started 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 ofEntity1 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)   or   e1.Entity2Colection.Remove(e2)

    '   save

    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 may-to-many relationships with each of 2 or more other entities--for instance,

    Entity 1 *:* Entity2,

    Entity1 *:* Entity3, and

    Entity1 *:* 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?


    Robert Gustafson


    Robert Gustafson


    Wednesday, December 14, 2016 12:51 AM