joining two tables in entity framework

c# entity-framework linq sql

Popular Answer

In order to do a LINQ join, the types on either side of the equals sign must exactly match, however your query uses USER ID instead of userId.

The simple fix is:

 var fav = from favs in db.FAVORITES
           join pins in db.PINS
               on new { favs.USER_ID, favs.PIN_ID } 
               // 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 };

If you use the fluent syntax for GroupJoin (which is what you are actually doing here because of the "into" phrase; ordinary Join is similar), it will be a little easier to understand why this is essential.

This is the signature:

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

Keep in mind that both the outerKeySelector and the innerKeySelector must return TKey (the join will then be done by matching these keys).

You would need to: To write your original join in the fluid style.

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);
2/13/2014 4:28:30 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow