代码之家  ›  专栏  ›  技术社区  ›  jmogera

具有两个独立DBContext的实体框架

  •  0
  • jmogera  · 技术社区  · 14 年前

    我正在使用实体框架4,并且我收到了以下错误:

    无法插入外键值,因为对应的主键 键值不存在。[外键约束名称= FK_表1_表2_列Id]

    哪里 Table1 是一体的 DBContext 以下为:

    public class Database1DB : DbContext
    {
       public DbSet<Table1> TableOne { get; set; }
    }
    

    Table 2 在另一个 DBContext(数据库内容) 以下为:

    public class Database2DB : DbContext
    {
       public DbSet<Table2> TabeTwo {get;set;}
    }
    

    Table 1 具有对的外键引用 Table2 的列如下所示:

    public class Table1
    {
       [Key]
       public int Id {get;set;}
    
       [ForeignKey("Table2")
       public int ColumnId {get;set;}
    
       public virtual Table2 Table2 {get;set;}
    }
    
    public class Table2
    {
       [Key]
       public int Id {get;set;}
    }
    
    1 回复  |  直到 14 年前
        1
  •  3
  •   Ladislav Mrnka    14 年前

    不能对在不同上下文中定义的实体之间的关系进行建模。相关实体必须在相同的上下文中才能使其工作。在您的情况下,您可以简单地使用:

    public class Table1
    {
       [Key]
       public int Id {get;set;}
       public int ColumnId {get;set;}
    }
    
    public class Table2
    {
       [Key]
       public int Id {get;set;}
    }
    

    您将不得不手动处理关系。