Search code examples
entity-framework-4many-to-manyentity-framework-ctp5

Populating a linking table in a many-to-many relationship


I am trying to get to grips with EF4 CTP5. I have two classes that have a many-to-many relationship: Member and MemberGroup. CTP5 Code First generated two tables (Members and MemberGroups) and also a third named MemberGroupMembers that has two columns (MemberGroupId and MemberId) So far everything is as I was expecting it to be. I have seeded the database with some Members and MemberGroups. The problem is that I cannot find how to assign one or more MemberGroups to a Member, which would result in inserting a row into the MemberGroupMembers table for each MemberGroup that the Member is assigned to.

    public class Member
{
    public int Id { get; set; }

    public Guid SecureId { get; set; }

    public DateTime JoinedOn { get; set; }

    public virtual ICollection<MemberGroup> MemberGroups { get; set; }
}

public class MemberGroup
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime CreatedOn { get; set; }

    public virtual ICollection<Member> Members { get; set; }
}

public class CTP5testContext : DbContext
{
    public CTP5testContext() : base("CTP5test") { }

    public DbSet<Member> Members { get; set; }

    public DbSet<MemberGroup> MemberGroups { get; set; }
}

public class CTP5testContextInitializer : DropCreateDatabaseIfModelChanges<CTP5testContext>
{
    protected override void Seed(CTP5testContext context)
    {
        new List<Member>
        {
            new Member
            {
                Id = 1,
                SecureId = Guid.NewGuid(),
                JoinedOn = DateTime.Now
            }
            ,
            new Member
            {
                Id = 2,
                SecureId = Guid.NewGuid(),
                JoinedOn = DateTime.Now
            }
        }.ForEach(m => context.Members.Add(m));

        var memberGroup = new MemberGroup()
        {
            Id = 1,
            Name = "MemberGroup 1",
            CreatedOn = DateTime.Now
        };

        context.MemberGroups.Add(memberGroup);

        // How can I assign Member 1 to MemberGroup 1 ?????

        context.SaveChanges();
    }
}

I hope that it is clear what I am trying to do here and that someone can give me an example of how to achieve this.

Regards, Erwin


Solution

  • You must use collections defined in your POCO classes. So if you want to assign member1 to memberGroup you will simply call:

    memberGroup.Members.Add(member1);