Reputation: 1
I have 2 tables, it is a 1-1 relationship
Table1
Table1Id(primarykey)
Table2Id(foreign key)
Colum1
Column2
Table2
Table2Id(primarykey)
Colum1
Column2
I am wanting to set this up in entity frame work code first either using data annotations or fluent api
I have tried several ways but always get a foreign key insert error when trying to insert a single table2 entity because there is no link to table 1 or it creates a bridge table which is not needed
Both table primary keys also require identitySpec and are integers
What properties in the model should be decorated with what attributes or the fluent API lambda expressions?
Upvotes: 0
Views: 42
Reputation: 742
If I understand good, you want to make a 1 to 1 relationship right? So, one way to do that could be:
public class Table1
{
[Key]
public int Table1Id { get; set; }
public string Column1 { get; set; }
public string Column2 { get; set; }
public virtual Table2 Table2 { get; set; }
}
public class Table2
{
[ForeignKey("Table1")]
public int Table2Id { get; set; }
public string Column1{ get; set; }
public string Column2{ get; set; }
public virtual Table1 Table1 { get; set; }
}
You have to consider that in one-to-one relationship, the primary key from the first entity is the primary key and foreign key (at the same time) of the second one.
Upvotes: 0