views:

506

answers:

1

I am trying to write an extention method for a repository. The repository has a method IQueryable<parent> GetAll(). I want to create an extention method FilterByChildId(int childId) so that I can write:

List<parent> data = from d in repository.getAll().FilterByChildId(33).ToList()

Not sure how to do the join on the parent and child inside the extension method. I thoudht it would be something like:

public static IQueryable<parent> FilterByChildId(
  this IQueryable<parent> query, 
  int id)
{
  return from data in query where data.child.id == id select data
}

but not a chance. I tried all sorts of variations using join, groupjoin but not clicking. Any help would be appreciated.

+2  A: 

I would essentially write the same as you did.

public static IQueryable<Parent> FilterByChildId(
   this IQueryable<Parent> parents, Int32 id)
{
   return parents.Where(p => p.Child.Id == id);
}

Just checked it with one of my Entity Framework models and it works. I assumed a simple many (parent) to one (child) relationship as your code indicates. Note that this is a bit confusing - many parents for one child. Could it be that you have a many to many relationship? One parent might have many childs and one child might have multiple parents? Then the proeprty Childs (child in your code) would be a collection and the code must be changed as follows.

public static IQueryable<Parent> FilterByChildId(
   this IQueryable<Parent> parents, Int32 id)
{
   return parents.Where(p => p.Childs.Any(c => c.Id == id));
}

The third posibility is one parent with many childs. The second method will work for this case but always return at most one parent assuming the child ids are unique.

Daniel Brückner