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
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.