Levi Botelho
Levi Botelho

Reputation: 25214

Entity Framework - Foreign key in sub-object

I am working with Entity Framework to retrive blog data from a database. I have a class "BlogPost" and a class "Author". One Author may have many blog posts, but the Author object itself does not contain a list of them. As far as the Author object is concerned, it is independent of all blog posts.

An instance of the Author class is included as a property in the BlogPost. Every author has an AuthorId. I would like to pull from my database a given blog and have the Author object filled with the pertinent data. I have managed to do this by including an AuthorId property in my BlogPost class, using the following code to map the object:

this.HasRequired(t => t.Author).WithMany().HasForeignKey(x => x.AuthorId);

What I would like to do, however, is to be able to do the same thing but without having to include the AuthorId property directly in the model. The reason being, is because as the Author object contains the coresponding ID already, I am repeating the same piece of information twice. I would like to do something along these lines:

this.Property(t => t.Author.Id).HasColumnName("id_user");
this.HasRequired<TwitterUser>(t => t.Author).WithMany().HasForeignKey(t => t.Author.Id);

So, is there any way do retrieve the Author sub-object without having to store the AuthorID redundantly in the BlogPost object alongside the Author object itself?

Upvotes: 0

Views: 599

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

The syntax you are using is called "foreign key associations", and was introduced in EF 4 because it solves a number of problems. For example, when using FK Associations you can perform cascaded deletes automatically.

You can read more about them here:

http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx

You can still do things the old way, with simple navigational properties. But you will need to a slightly different syntax. One thing is that independent associations require that you have navigational properties on both ends, and you said you only wanted this one-way. So you are stuck either adding an association to your Author entity, or using FK associations.

You may also find this article by our own Ladislav Mrnka useful:

http://www.ladislavmrnka.com/2011/05/foreign-key-vs-independent-associations-in-ef-4/

Also note, that according to the EF team, Independent Associations can perform much worse than FK Associations, although it seems this is limited to View Generation, so it's a one-time startup cost (each time you start the app or app domain). Also, for small models you probably won't notice it.:

http://msdn.microsoft.com/en-us/data/hh949853.aspx

EDIT:

As was pointed out by @Slauma, you can map an independent association by using the .Map property like so:

this.HasRequired(t => t.Author).WithMany().Map(m => m.MapKey("AuthorId"));

Upvotes: 1

Related Questions