I am using Entity Framework 4, and I am getting this error:
A foreign key value cannot be inserted because a corresponding primary
key value does not exist. [ Foreign key constraint name =
FK_Table1_Table2_ColumnId ]
Where Table1 is in one DBContext:
public class Database1DB : DbContext
{
public DbSet<Table1> TableOne { get; set; }
}
and Table 2 is in another DBContext:
public class Database2DB : DbContext
{
public DbSet<Table2> TabeTwo {get;set;}
}
Table 1 has a foreign key reference to Table2‘s column like this:
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;}
}
You cannot model relations between entities defined in different contexts. Related entities must be in the same context to make it work. In your case you can simply use:
And you will have to handle relation manually.