marcusstarnes
marcusstarnes

Reputation: 6531

Fluent NHibernate Mapping for a Category / Sub-Categories Tree

I have the following model class for my 'Category' object:

public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Category ParentCategory { get; set; }

public virtual IList<Category> SubCategories { get; set; }

This is my fluent nhibernate mapping class for 'Category':

Id(x => x.Id).GeneratedBy.Native();

Map(x => x.Name);
References(x => x.ParentCategory).Column("ParentCategoryId");

// ** THE BELOW MAPPING IS WHAT I'M UNSURE ABOUT **
HasMany(x => x.SubCategories).Where(x => x.Id == x.ParentCategory.Id);

My database that this relates to consists of a number of 'categories', some of which are at root level (and have a ParentCategoryId = NULL) and all others are sub-categories, which may be only 1 level deep, or may be 3,4,5 levels deep (recursive parents back up to a root/parent CategoryId.

Example of relationship between rows/records:

Cars (Id = 1 - ParentCategoryId = NULL)
Cars (Id = 1) > Hatchback (Id = 2 - ParentCategoryId = 1)
Cars (Id = 1) > Hatchback (Id = 2) > Ford (Id = 3 - ParentCategoryId = 2)

Motorcycles (Id = 4 - ParentCategoryId = NULL)
Motorcycles (Id = 4) > Scooters (Id = 5 - ParentCategoryId = 4)

The 'SubCategories' property within my Category class needs to retrieve all Categories that have a 'ParentCategoryId' of the current Category(Id), but I'm unsure how I go about mapping this. I've tried the HasMany mapping shown in the above example, but that failed.

Upvotes: 3

Views: 1066

Answers (1)

marcusstarnes
marcusstarnes

Reputation: 6531

I believe I have just implemented a working solution to this by changing the HasMany mapping to the following:

HasMany(x => x.SubCategories)
.Cascade.AllDeleteOrphan()
.KeyColumn("ParentCategoryId")
.Where(x => x.ParentCategory.Id == x.Id)

Upvotes: 3

Related Questions