joining two tables in entity framework

30,200

When doing a LINQ join, the types on either side of equals must be exactly the same, but in your query you have USER_ID vs. userId.

The fix is simply:

 var fav = from favs in db.FAVORITES
           join pins in db.PINS
               on new { favs.USER_ID, favs.PIN_ID } 
               equals 
               // use explicit naming so the first property gets the name USER_ID not userId
               new { USER_ID = userId, pins.PIN_ID } 
               into res
           from r in res
           select new { favs.PIN_ID, r.TYPE_ID };

It's a bit easier to see why this is necessary if work with the fluent syntax for GroupJoin (what you're actually doing here due to the "into" clause; regular Join is similar).

The signature is:

public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
    this IQueryable<TOuter> outer,
    IEnumerable<TInner> inner,
    Expression<Func<TOuter, TKey>> outerKeySelector,
    Expression<Func<TInner, TKey>> innerKeySelector,
    Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector
)

Note that outerKeySelector and innerKeySelector must return the same type TKey (the join will then be done by matching these keys).

To write your original join in the fluent style, you'd have:

var fav = db.FAVORITES.GroupJoin(
    inner: inner,
    // the return types of the selectors don't match, so the compiler can't
    // infer a type for TKey!
    outerKeySelector: favs => new { favs.USER_ID, favs.PIN_ID },
    innerKeySelector: pins => new { userId,       pins.PIN_ID },
    resultSelector: (favs, res) => res.Select(r => new { favs.PIN_ID, r.TYPE_ID })
)
.SelectMany(res => res);
Share:
30,200
a3adel
Author by

a3adel

Updated on July 09, 2022

Comments

  • a3adel
    a3adel almost 2 years

    i'm trying to join two tables in entity framework and get the value from one of them to do another query on a third table this is the query i'm using

      var fav = from favs in db.FAVORITES
    
                          join pins in db.PINS
                          on new { favs.USER_ID, favs.PIN_ID } equals new { userId, pins.PIN_ID } into res
                          from r in res
                          select new { favs.PIN_ID, r.TYPE_ID };
    

    but it gives me a syntax error in The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin' i have searched about the error and find that the people always say to make sure that the properties in the equals clause are the same type, and yes the are all of type non nullable int