Reputation: 10604
Basically put, I have an "Identity" table that has an ID and username, I have another table that has entries "owned" by a person, for that reason, I need to have a FK that links to the Identity table.
For example: Class "Identity" - int ID, string username.
I was just wondering which of the following is best:
Class "test" - int ID, string data, Identity identity
Class "test" - int ID, string data, int identity_id
- with an annotation defining as foreign key.
I personally use the first, and seen that EF basically does the second behind the scene, but I was just wondering what the advantages/disadvantages are and what is best?
Upvotes: 2
Views: 234
Reputation: 364279
From the object oriented perspective the first is better because you have reference to the related object and it is what you expect when working with objects. In database this is performed by foreign key which defines relation between two records.
Entity framework offers both correct object oriented approach (the first one) and the approach where you include foreign key property in the entity as well. The reason is that exposing FK property will make some operations much more easier. Most common solution for the second approach is:
public class Test
{
public int Id { get; set; }
public string Data { get; set; }
[ForeignKey("Identity")]
public int IdentityId { get; set; }
public Identity Identity { get; set; }
}
You have both access to FK property and the entity. Those approaches have names: Independent association (the first one) and Foreign key association (the second one). There are more differences between them - I described them in another answer.
Upvotes: 3