TMan
TMan

Reputation: 4122

How to insert using many to many relationship with entity framework

I'm trying to set up an many to many relationship with groups and students, so students can be assigned to many groups and groups can have many students assigned to it. I keep getting an error when I go to call context.savechanges(). In my objects I do have proper configuration, virtual ICollection in both. My configuration is as follows:

public class DataContext : DbContext
{
    public DbSet<Student> StudentsContext { get; set; }
    public DbSet<Group> GroupsContext { get; set; }
    public DbSet<Phase> PhaseContext { get; set; }
    public DbSet<Admin> AdminContext { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Student>()
            .HasMany(g => g.Groups)
            .WithMany(s => s.GroupMembers)
            .Map(x => x.MapLeftKey("StudentId")
                .MapRightKey("GroupId")
                .ToTable("Student_XRef_Group"));

    }
}

Then in controller just as a test I would try:

        var phase = phaseRepository.Select().SingleOrDefault(x => x.PhaseId == phaseId);

        phase.Groups.Clear();

        //Testing
        Group testGroup = new Group();
        testGroup.GroupNumber = 1;

        testGroup.GroupMembers.Add(AllStudents[0]); //Students of type Student
        phase.Groups.Add(testGroup);
        //Testing

        context.SaveChanges();

Then when it reaches context.savechanges I get the following error:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

** SOLVED ** Turns out that by me calling phase.Groups.clear() was the problem, why I do not know. I was hoping maybe can now tell me why?

Upvotes: 1

Views: 1240

Answers (1)

ChrisO
ChrisO

Reputation: 5465

Calling Clear() on your collection in this case only attempts to detach the relationship between the Phase and the Group and not actually delete the objects. You're therefore attempting to set the foreign key reference for each one to null, hence the non-nullable exception.

I can understand where the confusion comes from, after all we can use phase.Groups.Add(...) to add a new entity but it's important to remember that it does not work the other way around for Remove() and Clear().

To achieve what you want, you can use DeleteObject() on each Group to want to delete:

context.Groups.DeleteObject(groupToDelete);

Upvotes: 3

Related Questions