EF 4.2 Code first, how to delete many-to-many association?

I created a many-to-many relationship between two classes.

public class Member
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid MemberId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Group> Groups { get; set; } 

    public Member()
    {
        Groups = new HashSet<Group>();
    }
}

public class Group
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid GroupId { get; set; }
    public string Name { get; set; }

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

    public Group()
    {
        Members = new HashSet<Member>();
    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Group>().HasMany(x => x.Members).WithMany(c => c.Groups)
        .Map(y =>
                 {
                     y.MapLeftKey("GroupId");
                     y.MapRightKey("MemberId");
                     y.ToTable("Group_to_Member");
                 });
}

This works if i test it:

var member = new Member();
member.Name = "Smith";
db.Members.Add(member);

var group = new Group();
group.Name = "Group 1";
db.Groups.Add(group);

member.Groups.Add(group);
group.Members.Add(member);

db.SaveChanges();

But how can i delete a member from a group? I tried this: var group = db.Groups.First(); db.Groups.Remove(group); db.SaveChanges();

I just keep getting "The DELETE statement conflicted with the REFERENCE constraint". So how can i tell it to first remove the association and then the entry?

Answers


See comment from RedHat regarding setting the FK in the database to cascade on delete.


Need Your Help

VBA Duplicate Sheet with code

excel vba excel-vba

So I have an Excel workbook that contains a template sheet for products.

Rails join two tables or replace numbers by the words

mysql ruby-on-rails

I want to write logs to the database and I have often repeated words (syslog, sms, voice, email), I need to instead these words insert numbers (syslog - 1, sms - 2, voice - 3, email - 4), so as not...