我有四个模型,即家庭、母亲、父亲、学生,我试图将父亲和母亲和学生与家庭表和学生表与母亲和父亲表相关联。此处家庭表包含有关家庭的信息。Mother 和 Father 表包含他们的个人信息,Student 表包含学生信息 + MotherID 和 FatherID。这意味着家庭表是母亲和父亲的主要表,学生表。Mother表的MotherID和父亲表的FatherID被引用到Student表。
我首先使用 MVC 4 实体框架代码,
这些是我的模型类。
public class Family
{
public int FamilyID { get; set; }
public string FamilyName { get; set; }
public virtual ICollection<Mother> Mothers { get; set; }
public virtual ICollection<Father> Fathers { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Mother
{
public int MotherID { get; set; }
public int FamilyID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual ICollection<Student> Students{ get; set; }
}
public class Father
{
public int FatherID { get; set; }
public int FamilyID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public int FamilyID { get; set; }
public int MotherID { get; set; }
public int FatherID { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public virtual Family Families { get; set; }
public virtual Mother Mothers { get; set; }
public virtual Father Fathers { get; set; }
}
数据库上下文类:
public class MYContext:DbContext
{
public DbSet<Family> Families { get; set; }
public DbSet<Mother> Mothers { get; set; }
public DbSet<Father> Fathers { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
//base.OnModelCreating(modelBuilder);
}
}
编写完上述代码后,我只是在包管理器控制台上运行了以下命令。
PM> Add-Migration InitialContext
它为我创建了一个 InitialContext.cs 类。
PM> Update-Database -Verbose
它在下面给我一个错误
Introducing FOREIGN KEY constraint 'FK_dbo.Student_dbo.Mother_MotherID' on table
'Student' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON
UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
我究竟做错了什么??
为什么我收到这个错误???请帮我一个!
首先使用EF代码实现一对多和多对多关系的正确方法是什么?请用这个例子指导我。