[英]joining two tables in 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
进行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);
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();
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()
吗?因为您的模型将允许客户/描述与多个帐户相关)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.