2
votes

How do I create a one to many mapping which has a bridge table in the middle?

I basically have 3 tables: Items, Tags, and TagsToItems.

Each Item can have many Tags as defined by the TagsToItems table. How do I set up this mapping correctly using Fluent NHibernate?

I've been playing with HasMany but haven't quite figured out how this works with a bridge table.

HasMany(x => x.Tags).Table("TagsToItems").KeyColumn("ItemId");

My latest attempt to solve this problem looks like this:

HasManyToMany(x => x.Tags)
                .AsBag()
                .Table("TagsToItems")
                .ParentKeyColumn("ItemId")
                .ChildKeyColumn("TagId")
                .Cascade.All()
                .Inverse();

However this is throwing the error:

Initializing[Namespace.Item#11]-failed to lazily initialize a collection of role: Namespace.DataAccess.NHibernate.Entities.Item.Tags, no session or session was closed

1

1 Answers

1
votes

It turns out that the problem is with using the Tags collection associated to an Item.

The Tags collection could not be lazily initialised because by the time I was trying to use it (in my view) the session scope of the NHibernate session had closed.

I solved this by setting .Not.LazyLoad() on the mapping:

HasManyToMany(x => x.Tags)
                .AsBag()
                .Table("TagsToItems")
                .ParentKeyColumn("ItemId")
                .ChildKeyColumn("TagId")
                .Not.LazyLoad()
                .Cascade.All();