c# - C# Linq 使用 where 子句压缩连接查询
问题描述
嗨,我正在使用下面的代码使用 linq 语法从 2 个表中获取所需的数据,这工作正常。
var ratings = from r in _ratingRepository.AsQueryable()
join c in _convRepository.AsQueryable()
on r.SessionId equals c.CurrentConversationSid
where!c.IsDeleted && c.DateCreated >= request.From && c.DateCreated <=
request.To && c.HasRated
select new Rating() {
Id = r.Id,
SessionId = r.SessionId,
Questions = r.Questions,
AvgRatingValue = r.AvgRatingValue
};
我想使用以下语法转换此代码
IQueryable<Rating> ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable().Where(a => a.HasRated), r => r.SessionId, c => c.CurrentConversationSid, (r, c) =>
new Rating()
{
Id = r.Id,
SessionId = r.SessionId,
Questions = r.Questions,
AvgRatingValue = r.AvgRatingValue
});
它给出以下错误
System.ArgumentException:'
1[Flecx.Chat.Entities.Conversation]' cannot be used for parameter of type 'System.Linq.IQueryable
System.Linq.IQueryable 1[Flecx.Chat.Entities.Conversation] 方法的'System.Collections.Generic.IEnumerable 1[Flecx.Chat.Entities.Conversation]'类型的表达式1[Flecx.Chat.Entities.Conversation] Where[Conversation](System.Linq.IQueryable
,System.Linq。 Expressions.Expression1[System.Func
2[Flecx.Chat.Entities.Conversation,System.Boolean]])'(参数'arg0')'
如果我删除此代码 .Where(a => a.HasRated) 它运行良好。如何在上述语法中包含 where 子句。
需要帮忙
解决方案
尝试这个:
var ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable(),
r => r.SessionId,
c => c.CurrentConversationSid,
(r,c)=>new {r,c}) //**
.Where(a => a.c.HasRated)
.Select(x => new Rating()
{
Id = x.r.Id,
SessionId = x.r.SessionId,
Questions = x.r.Questions,
AvgRatingValue = x.r.AvgRatingValue
});
您可以使用下面的“//**”过滤任何您想要的内容:
(r, c) => new
{ r.Id,
r.SessionId,
r.Questions,
r.AvgRatingValue,
c.HasRated
}
然后您的代码更改为:
var ratingsObj = _ratingRepository.AsQueryable()
.Join(_convRepository.AsQueryable(),
r => r.SessionId,
c => c.CurrentConversationSid,
(r, c) => new
{ r.Id,
r.SessionId,
r.Questions,
r.AvgRatingValue,
c.HasRated})
.Where(a => a.HasRated)
.Select(x => new Rating()
{
Id = x.Id,
SessionId = x.SessionId,
Questions = x.Questions,
AvgRatingValue = x.AvgRatingValue
});
推荐阅读
- python - 从令牌(FunctionDef)构建 AST?
- php - 如何列出目录中的所有图像并将它们包含在 php 中
- python - 如何使用 selenium 定期从网站获取记录?
- javascript - Mocha.js:所有测试完成后如何运行一些代码?
- sockets - 有没有办法使用 iptables 更改本地端口绑定?
- java - Android Studio中的setText到TextView不起作用
- java - Micronaut Kotlin 项目的 IntelliJ 中缺少 javax.inject 导入
- javascript - 向下滚动时标题淡入显示向上滚动脉冲
- python - pikepdf - 如何从 django 视图返回内存中的 pdf 对象
- log4j - log4j2如何选择会话而不是日期