在实体框架中连接两个表

时间:2014-02-13 16:15:12

标签: c# sql linq entity-framework

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

  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”时类型推断失败 我搜索了错误并发现人们总是说要确保 equals 子句中的属性是相同的类型,是的,所有类型都是非可空的int

2 个答案:

答案 0 :(得分:3)

在进行LINQ连接时,equals两侧的类型必须完全相同,但在查询中,您有USER_ID与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类似),可以更容易理解为什么这是必要的。

签名是:

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(然后通过匹配这些键来完成连接)。

要以流畅的方式编写原始联接,您需要:

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

答案 1 :(得分:-3)

你可以试试这个:

var balance = (from a in context.Accounts
           join c in context.Clients on a.UserID equals c.UserID
           where c.ClientID == yourDescriptionObject.ClientID
           select a.Balance)
          .SingleOrDefault();

或 - 如果您只有DescriptionID:

var balance = (from a in context.Accounts
           join c in context.Clients on a.UserID equals c.UserID
           join d in context.Descriptions on c.ClientID equals d.ClientID
           where d.DescriptionID == yourDescriptionID
           select a.Balance)
          .SingleOrDefault();

(或FirstOrDefault()ToList()Sum()?因为您的模型允许客户/说明与多个帐户相关)

相关问题