Yogi Bear
Yogi Bear

Reputation: 963

entity framework configuration addorupdate many-to-many seed records

Defining the many-to-many relationship is not the problem. I have a Rooms table (like rooms in a house) and each of these can have one or more colors from a Colors table.
Each has a List reference to the opposite table - see classes below.

In the Configuration class, Seed method, I am creating the various tables using AddOrUpdate.

            ctx.Rooms.AddOrUpdate(r => new { r.Name, r.HouseId },
            new Room
            {
                Name = "Kitchen",
                House = (from h in ctx.Houses where h.Address == "Littleton, MA" select h).First(),
                HouseId = (from h in ctx.Houses where h.Address == "Littleton, MA" select h.HouseId).First()
            });

(followed by ctx.SaveChanges of course)

And I can create many colors the same way:

            ctx.Colors.AddOrUpdate(c => new { c.ColorName },
            new Color
            {
                ColorName = "Green"
            });

With each room, I want to associate one or more of the colors.

enter image description here (In SQL:) enter image description here Colors: enter image description here enter image description here

EF creates the table relating the two in the many-to-many relationship.

enter image description here

It seems like this should be easy, but I can't find a way and I have searched the web as well. Thanks for your help. :-)

Upvotes: 0

Views: 265

Answers (1)

Fran
Fran

Reputation: 6520

Make sure you are initializing your list in the Room constructor

public class Room
{
   public Room()
   {
      Colors = new List<Color>();
   }
   // properties omitted
   public virtual IList<Color> Colors {get;set;}
}

Then just call

room.Colors.Add(Color color);

This is will add a color to your list.

This isn't the best solution as you should encapsulate your collections so that your aren't bypassing any business rules but EF 6 makes it difficult.

EF core makes it much easier.

Upvotes: 1

Related Questions