实体框架有两个独立的DBContext

时间:2012-08-06 15:42:44

标签: asp.net asp.net-mvc-3 entity-framework-4

我正在使用Entity Framework 4,我收到此错误:

  

无法插入外键值,因为相应的主键   键值不存在。 [外键约束名称=   FK_Table1_Table2_ColumnId]

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 1Table2列的外键引用,如下所示:

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 个答案:

答案 0 :(得分:3)

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

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

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

你必须手动处理关系。