我試圖建立與團體和學生的多對多關係,因此學生可以被分配到許多組和分組,可以有很多學生分配到它。當我去調用context.savechanges()時,我不斷收到錯誤。在我的對象中,我確實有適當的配置,在兩者中都有虛擬ICollection。我的配置如下:如何插入使用與實體框架的多對多關係
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"));
}
}
然後在控制器只是作爲測試我會嘗試:
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();
然後,當它達到context.savechanges我得到以下錯誤:
的操作失敗:由於一個或多個外鍵屬性不可空,因此無法更改關係。當對關係進行更改時,相關的外鍵屬性將設置爲空值。如果外鍵不支持空值,則必須定義新的關係,必須爲外鍵屬性指定另一個非空值,或者必須刪除不相關的對象。
**已解決** 原來,我通過調用phase.Groups.clear()是問題所在,爲什麼我不知道。我希望現在可以告訴我爲什麼?