简体   繁体   中英

How do you do additional filtering on a HasMany mapping in Fluent nHibernate?

In a project I'm working on, I have four entities(amongst a bunch of others), WorkOrder, Crew, CrewAssignment, and Contractor. Their relationship is like this:

  • A WorkOrder has one Contractor, which can be changed
  • A Crew only ever has one Contractor
  • A CrewAssignment only ever has one Crew
  • A WorkOrder has many CrewAssignments

The problem I'm having is setting up the last part where a WorkOrder can have multiple CrewAssignments. What I want to do is ensure that the WorkOrder.CrewAssignments property only returns the CrewAssignments that have a Crew with the same Contractor as the WorkOrder. Or, less wordy, "where WorkOrder.Contractor == CrewAssignment.Crew.Contractor".

The only thing I've been able to come up with is this, but it throws an exception about the x variable being undefined.

HasMany(x => x.CrewAssignments).KeyColumn("WorkOrderID").Where(x => x.Crew.Contractor == x.WorkOrder.Contractor);

Is doing something like this even possible? Or am I barking up the wrong tree entirely? Google's been failing me all morning with this one. Any ideas?

I don't know if it could help you but here is my take on in.

In FluentNHibernate you have a method called ApplyFilter that you can set up in your mappings in order to filter on child collections :

HasMany(x => x.CrewAssignments).KeyColumn("WorkOrderID").ApplyFilter<MyFilter>().Cascade.AllDeleteOrphan(); 

Then you can create your filter :

public class MyFilter: FilterDefinition
{
    public MyFilter()
    {
        WithName("contractor").WithCondition("Crew.ContractorId== :contractorId").AddParameter("contractorId", NHibernate.NHibernateUtil.Int32);
    }
}

Then in the implementation of your repository, you invoke the filter :

Sessions.EnableFilter("contractor").SetParameter("contractorId", 1254);

I don't know if this is the best solution but the only one that comes to my mind right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM