Reputation: 7449
Could you please explain this to me. Take this example:
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual StudentAddress Address { get; set; }
}
public class StudentAddress
{
[ForeignKey("Student")]
public int StudentAddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int Zipcode { get; set; }
public string State { get; set; }
public string Country { get; set; }
public virtual Student Student { get; set; }
}
I want to understand why we use the primary key in the dependent table as the foreign key, why don't we just follow the usual way: adding foreign column in the dependent table referring to the primary key from the principal table? And, can we reverse roles here, i.e. to use the primary key in Student entity as the foreign key?
Upvotes: 0
Views: 731
Reputation: 2226
Why don't we just follow the usual way: adding foreign column in the dependent table referring to the primary key from the principal table?
If we did that the relationship would be 1-n
, not 1-1
, as we could have more than one StudentAddress
with the same value of this field. By using the primary key as foreign key we make sure that we can't have more than one StudentAddress
with the same value (it would be a primary key violation).
So we make sure relational referential integrity does the work for us.
And, can we reverse roles here, i.e. to use the primary key in Student entity as the foreign key?
Then we should need to create first the StudentAddress
and then the Student
. We could have a StudentAddress
without having a Student
. As it is now, we can have a Student
without any StudentAddress
, but not the other way around. Makes more sense, I think. The StudentAddress
is a Weak Entity, which means that it can't exist unless the correspondent Student
exists.
These concepts and others about relationships between tables are usually well explained in any basic Relational Model book or course. You can implement EF code without knowing them in detail, but you will save yourself a lot of pain if you spend some time learning how to design a database model following some basic rules.
Upvotes: 2