Reputation: 1759
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;}
}
Upvotes: 0
Views: 521
Reputation: 364269
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:
public class Table1
{
[Key]
public int Id {get;set;}
public int ColumnId {get;set;}
}
public class Table2
{
[Key]
public int Id {get;set;}
}
And you will have to handle relation manually.
Upvotes: 3