使用EF Fluent API时遇到困难

时间:2012-04-15 16:51:45

标签: entity-framework entity-framework-4

我有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'。声明已被终止。“

我看不出我出错的地方

1 个答案:

答案 0 :(得分: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;}