Mapping a self-join to a collection in code first entity framework 4.3

Viewed 6434

I have a POCO class that maps to a self-joined table defined like this:

CREATE TABLE [dbo].[GalleryCategories](
    [CategoryID] [int] IDENTITY(0,1) NOT NULL PRIMARY KEY CLUSTERED,
    [Name] [nvarchar](256) NOT NULL,
    [ParentID] [int] NULL REFERENCES [dbo].[GalleryCategories] ([CategoryID]) ON DELETE NO ACTION ON UPDATE NO ACTION, 
)

I know there's a way to define a relationship using the model builder to reference a parent from a child... (e.g. like this)

But the class I'm trying to map looks like this...

public class GalleryCategory
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int? ParentID { get; set; }
    public List<Category> Subcategories { get; set; }
}

In other words, I'm trying to get Subcategories populated with all of the children - i.e. traverse down the hierarchy, not up the hierarchy.

Is there any way to do this using EF? This must be a FAQ somewhere but I couldn't find it after googling for an hour :-)

1 Answers
Related