views:

349

answers:

2

Is there a way that I filter out rows in a HasManyToMany mapping?

I have three tables (legacy, not able to change them) Service, Resource and ResourceService. The ResourceService allows multiple resources to link to multiple services but it also has an "Active" column.

On my Resource domain object I've mapped the services linked to the resource with a "ProvidedBy" property which returns an array of the services. The problem is that I only want rows from services that are marked as active.

Am I missing something basic here?

+2  A: 

Fluent NHibernate release 1.0 did not support NHibernate filters or filter-defs. I submitted a patch to James Gregory and team a while back which they have now incorporated in the trunk, so if you get the trunk rather than the release version you'll find the ability to do this sort of thing included.

Essentially, you can set up a class that inherits from FilterDefinition like so:

public class TestFilter : FilterDefinition
{
    public TestFilter()
    {
        WithName("test")
            .WithCondition("Age > :age")
            .AddParameter("age", NHibernateUtil.Int32);
    }
}

and then apply this filter in your fluent mapping:

HasManyToMany(x => x.Oldies)
    .Table("People")
    .ApplyFilter<TestFilter>();

You can set the parameter value and enable the filter using the session object as normal:

session.EnableFilter("test").SetParameter("age", 65);
David M
That seems pretty heavyweight given what i'm trying to do but if Fluent doesn't support any other method, I guess it's what I'll have to do!
Neil Ramsbottom
It's not so much a question of what Fluent supports but what NHibernate supports. You can always use an XML mapping file to define and apply your filter if you prefer... ;)
David M
A: 

Wouldn't this be a candidate for a Where?

HasManyToMany(x => x.Whatevers)
  .Where(x => x.Active);
James Gregory
I'm afraid not. The column that I wish to filter on is "ResourceService" table, which is the link table.I did give it a shot but the compiler doesn't like it: HasManyToMany(Function(o As Service) o.ProvidedBy) _ .Cascade() _ .All() _ .Table("ResourceService") _ .ParentKeyColumn("ServiceId") _ .ChildKeyColumn("ResourceId") _ .Where(Function(x As ResourceService) x.Active)
Neil Ramsbottom
Blasted formatting.
Neil Ramsbottom