Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Entity Framework 4.3 Poco object relationship zero to many

Posted on: 2012-03-22

If you have a relationship of zero to many your master object won't have in the database any reference to the detail object. It's the detail object that has foreign key to the master. But, on the C# class side, the master will have a collection of the detail.

To make this work, you need to have a repository that will do the include correctly if you want to use the eager loading.

 MyDbContext.Libraries.Include("Book"); 

You also need to specify the collection as ICollection. IEnumerator won't work and if you do, you will end up with an error. This property need to be also virtual.

 public virtual ICollection<Book> Books { get; set; } 

A specified Include path is not valid. The EntityType 'DataAccessLayer.Database.Book' does not declare a navigation property with the name 'BooksCollection'.