big_tommy_7bb
big_tommy_7bb

Reputation: 1317

Why does EF require the id of an entity as well as the reference

I've a question about Entity Framework. In a code first scenario I have a person class that references an address. In my domain I would have this as a reference to the Address class. All the examples of Entity Framework I've seen also require an AddressId field. This is something that I think shouldn't be there and isn't required in my domain driven model.

Why does EF require this? Can I do without it (I don't believe NHibernate requires this).

Thanks

public class Person()
{
    public int Id {get;set;}
    public string Name {get;set;}
    public Address Address {get;set;}
    public int AddressId {get;set;} //Entity Framework seems to require this
}

Upvotes: 0

Views: 73

Answers (2)

Sym Phys
Sym Phys

Reputation: 51

You should read up on Independent Association and Foreign Key Association: Code First: Independent associations vs. Foreign key associations?

A good article from the same author who answered the question above is also avialable at: foreign-key-vs-independent-associations-in-ef-4

Upvotes: 0

Pawel
Pawel

Reputation: 31610

Foreign keys are not required. In fact, support for foreign keys was introduced in EF4. Usually, FK are there for convenience. In many cases FKs help improve performance since you can change relationships without loading related entity if you know the id (one trip to database saved).

Upvotes: 1

Related Questions