0

I use the Entity Framework often, but I have one area of confusion I would like to understand better.

If I wanted to have a navigation property in an Entity such as

public virtual ExampleObject Example {get;set;}

it is also the done thing to have an Id property

public int ExampleId {get;set;}

My undertsanding is this creates a FK, but if I omit it, the functionality is the same and the FK seems to be created anyway. So, is there a reason for the additional field?

2

I've never used Entity Framework, nor am I familiar with it's implementation details, but it's quite common that ORMs will not resolve foreign keys into objects unless either they are explicitly instructed to do so or the user tries to access these objects. This makes sense - populating the Example property is much more expansive than populating ExampleId, since the ID is column of the containing entity's table but for the full ExampleObject you need to query another table.

While it seems like ExampleId is only useful for resolving the full ExampleObject, there can be cases where you need just the ID. For example, if Student has Course with the CourseId foreign key, and Assignment also has Course with the CourseId foreign key, you might want to use Student's CourseId directly to get all the Assignments with the same CourseId. You don't need the full Course object for that.

  • Makes sense having the ability to assign an Id rather than entire entity. Thanks. – James Jun 25 '14 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.