0

我有 4 个这样的表:

public class Table1
{
 public int Id {get;set;}
 public string Name {get;set;}
}

public class Table2
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table1Id {get;set;}
 public virtual Table1 {get; set;}
}

public class Table3
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table2Id {get;set;}
 public virtual Table2 {get; set;}
}

public class Table4
{
 public int Id {get;set;}
 public string Name {get;set;}
 public int Table3Id {get;set;}
 public virtual Table3 {get; set;}
}

我流利的 ​​API 是这样的:

modelBuilder.Entity<Table2>().HasRequired(x => x.Table1).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Table3>().HasRequired(x => x.Table2).WithMany().WillCascadeOnDelete(false);
modelBuilder.Entity<Table4>().HasRequired(x => x.Table3).WithMany().WillCascadeOnDelete(false);

当我尝试播种表时,出现此错误:

INSERT 语句与 FOREIGN KEY 约束“FK_Table4_Table3_Table3Id。冲突发生在数据库 MyDb、表“dbo.Table3”、列“Id”中。语句已终止。”

我看不到哪里出错了

4

1 回答 1

1

做这个...

modelBuilder.Entity<Table2>()
    .HasRequired(t => t.Table1)
    .WithMany() // t => t.AllTable2s)
    .HasForeignKey(t => t.Table1ID);

……最重要的是make it compile!:) (例如public virtual Table1 {get; set;}进入public virtual Table1 Table1 {get; set;}

于 2012-04-15T17:39:07.790 回答