简体   繁体   English

如何使用与实体框架的多对多关系插入

[英]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(). 当我去调用context.savechanges()时,我一直收到错误。 In my objects I do have proper configuration, virtual ICollection in both. 在我的对象中,我确实有适当的配置,虚拟ICollection。 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: 然后,当它到达context.savechanges时,我收到以下错误:

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. **已解决**原来我调用phase.Groups.clear()是问题,为什么我不知道。 I was hoping maybe can now tell me why? 我希望也许现在可以告诉我为什么?

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. 在这种情况下,对集合调用Clear()只会尝试分离PhaseGroup之间的关系,而不是实际删除对象。 You're therefore attempting to set the foreign key reference for each one to null, hence the non-nullable exception. 因此,您尝试将每个的外键引用设置为null,因此不可为空的异常。

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() . 我可以理解混淆的来源,毕竟我们可以使用phase.Groups.Add(...)来添加一个新的实体,但重要的是要记住它不适用于Remove()Clear()

To achieve what you want, you can use DeleteObject() on each Group to want to delete: 要实现所需,可以在每个组上使用DeleteObject()来删除:

context.Groups.DeleteObject(groupToDelete);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM