4

I'm using LinqKit PredicateBuilder (http://www.albahari.com/nutshell/predicatebuilder.aspx) for a method that do searching. This is how the relationships are built (Entity Framework 4 CPT 5 POCO):

public class MusicSheet
{
    [Key]
    public int ID { get; set; }
    public string Title { get; set; }
    public string Key { get; set; }

    public virtual ICollection<Author> Authors { get; set; }
}

public class Author
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Bio { get; set; }

    public virtual ICollection<MusicSheet> MusicSheets { get; set; }
}

I need to be able to build a predicate that checks for MusicSheet (the Title contains a specific search term) as well as the Name or Bio of the Author who might also contain that search term. Here is what I currently have:

var predicate = PredicateBuilder.False<MusicSheet>();
foreach (var term in terms)
{
    string keyword = term;

    predicate = predicate
    .Or(s => s.Title.Contains(keyword));
    // TODO Check for Author Name & Bio
}

Any suggestions? Thank you very much.

Saxman
  • 5,009
  • 11
  • 51
  • 72

1 Answers1

1

Have you tried this:

var predicate = PredicateBuilder.False<MusicSheet>();
foreach (var term in terms)
{
   string keyword = term;

   predicate = predicate
      .Or(s => s.Title.Contains(keyword) ||
               s.Authors.Any (a => a.Name.Contains(keyword) || a.Bio.Contains(keyword)));
}
Joe Albahari
  • 30,118
  • 7
  • 80
  • 91
  • Hi Joe, thank you very much for your help. I have a question on using the "`Or`" method. Should I do it the way you showed above, or something like this: `predicate = predicate.Or(s => s.Title.Contains(keyword)).Or(s => s.Authors.Any(a => a.Name.Contains(keyword))) ... ...` Or they effectively the same (using multiple `Or` vs. `||`)? Thanks again. – Saxman Feb 24 '11 at 15:49
  • I'd use the || operator when you can: the resultant expression tree will be simpler. – Joe Albahari Feb 25 '11 at 01:54