0

My models at the moment have all have an Id (primary key), but references to other models are made without use of numerical ids ie they are object references. I am expecting EF to supply the magic to make this work as I expect.. which it seems to be at the moment. However, I see a lot of questions and examples with explicit integer foreign keys. Am I missing something or expecting too much from the framework - or is this how its designed to be used?

1 Answer 1

2

You dont need to declare foreign keys explicitly. By default, EF code first will create a one to one relationship with an object reference and a one to many relationship with a collection of object references. The only thing that is required is a primary id.

Now declaring foreign keys explicitly might be convenient when having to map to a specific field or when wanting to work with foreign keys without including the relationships. In a project of mine, i also threat my entities (models in your case) as DTO's. Therefore i dont want relationships to exist. I use explicit foreign keys to load in other data like:

var student = service.GetStudent();
var class = service.GetClassById(student.ClassId);

It all depends on the requirements really and EF code first gives you a fine toolset of realizing what you need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.