14

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.

abatishchev
  • 92,232
  • 78
  • 284
  • 421
Elisabeth
  • 18,252
  • 48
  • 179
  • 303
  • 1
    possible duplicate of [Code First: Independent associations vs. Foreign key associations?](http://stackoverflow.com/questions/5281974/code-first-independent-associations-vs-foreign-key-associations) – Gert Arnold Feb 17 '13 at 10:58
  • 1
    @Gert I have read the article you have linked. Still I do not know wether I need both. When I have the entity reference I should also have the foreign key... so its just Repeating yourself... – Elisabeth Feb 17 '13 at 19:57
  • I think the information tells that you do not absolutely need `CustomerId` but you better do (although it's up to you). I also wanted to link you up with the terminology underlying your question and a body of sources that discuss it. – Gert Arnold Feb 17 '13 at 20:11
  • Here is another similar question: http://stackoverflow.com/questions/9253234/what-is-the-point-of-creating-foreign-key-properties-when-using-entity-framework – Slauma Feb 17 '13 at 21:08

1 Answers1

16

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.

Community
  • 1
  • 1
Ying
  • 2,392
  • 21
  • 20