【问题标题】:Having a difficulty with EF Fluent APIEF Fluent API 遇到困难
【发布时间】:2012-04-16 01:39:07
【问题描述】:

我有 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;}
}

而我的 fluent 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”。语句已终止。”

我看不到哪里出错了

【问题讨论】:

  • 你能显示“当我尝试为表格播种时”的代码吗?

标签: entity-framework entity-framework-4


【解决方案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;}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-02
    • 2019-03-03
    • 1970-01-01
    • 2011-07-25
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    相关资源
    最近更新 更多