none
Link to Entity join conditions

    Question

  • I'm having difficulty trying to join two tables with multiple column conditions.  It appears that I cannot AND two conditions on a join.

    Example:

    var price = from p in Context.Prices
          join i in Context.Items on p.PriceTemplate equals i.PriceTemplate && p.ItemId equals i.ItemId
    select ...

    The ANDed join condition fails whenit's included.

    Is it not possible to have more than 1 condition on a join?
    Friday, July 17, 2009 7:32 PM

Answers

  • Lee,

    LINQ supports equijoins with multiple keys using anonymous type syntax, like this:

    var price = from p in Context.Prices
                     join i in Context.Items on new {p.PriceTemplate,  p.ItemId } equals new {i.PriceTemplate, i.ItemId}
                     select p;

    Also, keep in mind that the names of the members of an annonymous type are part of the type definition, so if you need to join on two properties that have different names, you need to rename them:

    var price = from p in Context.Prices
                     join i in Context.Items on new {p.PriceTemplate,  p.ItemId } equals new {i.PriceTemplate, ItemId = i.Id}
                     select p;

    Hope this helps,
    Diego
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Saturday, July 18, 2009 6:13 AM

All replies

  • Lee,

    LINQ supports equijoins with multiple keys using anonymous type syntax, like this:

    var price = from p in Context.Prices
                     join i in Context.Items on new {p.PriceTemplate,  p.ItemId } equals new {i.PriceTemplate, i.ItemId}
                     select p;

    Also, keep in mind that the names of the members of an annonymous type are part of the type definition, so if you need to join on two properties that have different names, you need to rename them:

    var price = from p in Context.Prices
                     join i in Context.Items on new {p.PriceTemplate,  p.ItemId } equals new {i.PriceTemplate, ItemId = i.Id}
                     select p;

    Hope this helps,
    Diego
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Saturday, July 18, 2009 6:13 AM
  • Thanks!  I have never seen this documented.
    Monday, July 20, 2009 2:43 PM
  • Interesting. I cover this recipe in my book.

    3-17 3-17. Grouping by Multiple Properties

    I cover lot of other interesting recipes and answers to most common problems developers have faced with EF. link below shows the table of contents.

    http://weblogs.asp.net/zeeshanhirani/archive/2010/05/04/entity-framework-4-0-recipes-book.aspx

    Friday, May 07, 2010 5:21 AM