Tuesday, November 1, 2011

.Contains may sabotage LinqSpec working in tandem with NHibernate

Using .Contains in a LinqSpec Specification can create a query that NHibernate will not be able to support. The trouble comes when the .Contain trails an empty collection. I learned the hard way that this...

public static Specification<ProgramOffering> ProgramAndProgramPlanCriteria(

      IList<Guid> programIds, IList<Guid> programPlanIds)

{

   var programPlanSpec = new AdHocSpecification<ProgramOffering>(

         po => programPlanIds.Contains(po.ProgramPlan.Id) ||

         programIds.Contains(po.ProgramPlan.Program.Id));

   return programPlanSpec;

}

 
 

...had to be refactored to this...

public static Specification<ProgramOffering> ProgramAndProgramPlanCriteria(

      IList<Guid> programIds, IList<Guid> programPlanIds)

{

   List<Guid> programAndProgramPlanIds = new List<Guid>(){};

   programAndProgramPlanIds.AddRange(programIds);

   programAndProgramPlanIds.AddRange(programPlanIds);

   var programPlanSpec = new AdHocSpecification<ProgramOffering>(

         po => programAndProgramPlanIds.Contains(po.ProgramPlan.Id) ||

         programAndProgramPlanIds.Contains(po.ProgramPlan.Program.Id));

   return programPlanSpec;

}

 
 

...to account for situations in which one of the two collections handed in was flawed as hinted at here.

No comments:

Post a Comment