Arturo Ribes
Arturo Ribes

Reputation: 365

Entity Framework: include foreign key ID in entity?

I have read in many places that one should (usually) have the foreign key id in an entity because it is a database detail, and in fact, EF manages it pretty well by adding an EntityName_Id column to the corresponding table.

public class Order
{
    public decimal Total { get; set; }
    public int? InvoiceId { get; set; }
    public Invoice Invoice { get; set; }
}

public class Invoice
{
    public ICollection<Order> Orders { get; set; }
}

In this example, an Order has an optional relationship with Invoice. When showing info about Order, I am interested in knowing whether or not it has an Invoice.
The problem is that if I don't have the ´InvoiceId´ property in my entities, I have to check the whole related entity just to check if it exists, whereas having that property in my entity would allow me to check it for null, which is "free" in the sense that the entity is already loaded.

Is that the only use of having foreign key Id properties in entities? Am I missing something here?

Upvotes: 1

Views: 1822

Answers (1)

Red
Red

Reputation: 2776

You can check entity framework documentation to see answer for your question: https://msdn.microsoft.com/en-US/data/jj713564.aspx

It says:

With foreign key associations, you can use either method to change, create, or modify relationships. With independent associations, you cannot use the foreign key property.

Use cases provided in article:

  1. Update foreign key relationship -- this can cause issues if you update navigation property and foreign key at the same time and reference different objects.

    By assigning a new value to a foreign key property, as in the following example.

    course.DepartmentID = newCourse.DepartmentID;

  2. Remove foreign key relationship. This only works if there is no associated object with FK property, that is in state 'Added'.

    The following code removes a relationship by setting the foreign key to null. Note, that the foreign key property must be nullable.

    course.DepartmentID = null;

Apart from these cases you can use it to check if your reference is not null/null without really lazy-loading related entity like you said:

var isNull = course.DepartmentID == null;

I believe it's pretty much it. From my point of view, benefits from using FK property are too small to rely on them.

Upvotes: 1

Related Questions