I’m a Java guy and I’m working on learning the .Net realm. One of the things I’m learning is EF4, and I noticed this interesting thing. When you declare an entity with a 1:n relationship to another entity, you have to do something like this:
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
My question is:
Is there a good reason that the framework requires both declarations?
In the Java world, the framework is smart enough to figure out what the primary key is and adds that record to the DB without having to have a separate field on the entity class. Why didn’t .Net follow suit on this minor, but annoying, issue?
You don’t have to do that. In fact you shouldn’t because you can leave your object in an inconsistent state. Let’s say you have:
This is valid. You just need to tell EF in its configuration how to find the foreign key. Based on the above it will try to use
SomeClass.Category_Id, but you can change to it whatever you’d like.EDIT: If you want to change the foreign key you can do so by adding a configuration class and adding it during the
OnModelCreatingevent:In your overridden
Contextclass:Using the same classes above this would tell EF to look for a foreign key property called
SomeClass.CategoryIdinstead.