Skip to content

Self-referencing many-to-many relationships in Entity Framework 5 Code-First

by mstrid on August 27th, 2012

When trying to use the following POCO class to create the database schema using Entity Framework 5 Code-First the default data annotation mapping couldn’t handle the self-referencing many-to-many relationship that is specified by the RelatedProducts property.

image

The simple solution is to use the fluent API and add the following method to the DbContext class:

image

Now a join table is created automatically that handles the many-to-many relationship.

For more information see this article and this article.

Comments are closed.