joining two tables in entity framework

后端 未结 1 481
天命终不由人
天命终不由人 2020-12-21 14:11

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

  v         


        
相关标签:
1条回答
  • 2020-12-21 14:48

    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);
    
    0 讨论(0)
提交回复
热议问题