How do you do additional filtering on a HasMany ma

2019-04-16 06:03发布

问题:

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?

回答1:

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.