本文介绍了在实体框架中联接两个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在实体框架中联接两个表,并从其中一个表中获取值以对第三个表进行另一个查询这是我正在使用的查询

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 tablethis 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 };

但是它给我一个语法错误 join子句中的表达式之一的类型不正确.调用"GroupJoin"时类型推断失败我搜索了该错误,发现人们总是说要确保等于子句中的属性是同一类型,是的,所有类型都是non nullable int

but it gives me a syntax error inThe 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

推荐答案

进行LINQ连接时,equals两侧的类型必须完全相同,但是在查询中您具有USER_ID与userId.

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.

解决方法很简单:

 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 };

如果使用流利的GroupJoin语法(由于"into"子句您实际在此处执行的操作;常规Join与此类似),那么为什么需要这样做很容易.

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).

签名是:

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
)

请注意,outerKeySelector和innerKeySelector必须返回相同的TKey类型(然后通过匹配这些键来完成连接).

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);

这篇关于在实体框架中联接两个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:51