Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what scenarios do I need foreign keys AND navigation properties in entity framework

My Order class has:

public int CustomerId { get; set; }

public Customer Customer { get; set; }

Do I really need both properties to make a relation working?

I am not using disconnected entities, I am using code first approach.

like image 878
Elisabeth Avatar asked Feb 16 '13 22:02

Elisabeth


People also ask

What is the use of navigation properties in Entity Framework?

Navigation properties provide a way to navigate an association between two entity types. Every object can have a navigation property for every relationship in which it participates.

Does Entity Framework support foreign keys?

When you change the relationship of the objects attached to the context by using one of the methods described above, Entity Framework needs to keep foreign keys, references, and collections in sync.

Is it possible Entity Framework will support table without primary key?

The Entity framework will not support to have a table without primary key, but we can overcome this issue by accessing the table with additional column via a view and marking the new column as Primary in entity framework. Entity Framework requires primary keys for entities.

What are the different types of properties supported in Entity Framework?

An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.


1 Answers

According to Julia Lerman's book: Programming Entity Framework: DbContext, the difference lies at the difficulty of updating the navigation property. In page 85, She suggests "If there is one thing you can do to make your life easier in N-Tier scenarios, it’s to expose foreign key properties for the relationships in your model." The book includes samples for both scenarios.

The reason is that including a foreign key property tells Entity Framework to use Foreign Key Association, which is simpler than using the so-called Independent Association when you need to update the relationship, i.e., changing the order from one customer to another in your example. With foreign key association, all you need to do is changing the CustomerId. Without the CustomerId foreign key, you need more steps. The independent association uses the ObjectStateManager that is explained Code First: Independent associations vs. Foreign key associations? The ObjectStateManager is complex and is not even exposed from DbContext API.

like image 98
Ying Avatar answered Sep 21 '22 13:09

Ying