none
LinqToSql query question RRS feed

  • Question

  • Hi everyone!

    I've beens struggling with a query scenario for sometime now. It's regarding a Many-to-Many scenario with 3 tables:

    Persons
    Tags
    PersonsTags

    I have a search scenario where I want to return matches of persons in the case that the searchstring:
    a) matches a "Name" field in the Persons table
    and / or
    b) matches a "TagText" field in the PersonsTags table

    I can't seem to figure this out so any help or points in the right direction would be great!

    //Magnus
    Monday, June 1, 2009 11:52 AM

Answers

  • If TagText is in the TagText table, then do this:

      db.Persons.Where (p => p.Name == "Bloggs" && p.PersonTags.Any (pt => pt.TagText == "Foo"))

    Otherwise, if it's in the Tag table:

      db.Persons.Where (p => p.Name == "Bloggs" && p.PersonTags.Any (pt => pt.Tag.TagText == "Foo"))




    Write LINQ queries interactively - www.linqpad.net
    • Marked as answer by MagnusJonsson Monday, June 1, 2009 12:36 PM
    Monday, June 1, 2009 12:22 PM
    Answerer

All replies

  • If TagText is in the TagText table, then do this:

      db.Persons.Where (p => p.Name == "Bloggs" && p.PersonTags.Any (pt => pt.TagText == "Foo"))

    Otherwise, if it's in the Tag table:

      db.Persons.Where (p => p.Name == "Bloggs" && p.PersonTags.Any (pt => pt.Tag.TagText == "Foo"))




    Write LINQ queries interactively - www.linqpad.net
    • Marked as answer by MagnusJonsson Monday, June 1, 2009 12:36 PM
    Monday, June 1, 2009 12:22 PM
    Answerer
  • Thanks for the quick reply! It works now!

    //Magnus
    Monday, June 1, 2009 12:37 PM