lambda 怎么做联合查询?

davidtsui 2012-09-23 09:14:16
我有两个关联的实体,关系如下:



public class Answer
{
public int Id { get; set; }
public string Content{ get; set; }
public string Poster { get;set; }
public int QuestionId { get; set; }

public Question Question { get; set; }
}

public class Question
{
public int Id { get; set; }
public string Content { get; set; }
public List<Answer> Answers { get; set; }
}




现在我有三个问题:

1. 假如我知道了某个 Answer 的 id,怎么用 lambda 查询出对应的 Question?



int answerId = 2;
var result = context.Question.AsQueryable();

result = result.Where(p=>p.?); // 这里面该怎么写呢?



2. 假如我知道了某些 Answer 的 id,怎么用 lambda 查询出它们对应的 Question?



int[] answerIds = { 1, 2, 4, 6, 11 };
var result = context.Question.AsQueryable();

result = result.Where(p=>p.?); // 这里面该怎么写呢?




3. 如果知道 Answer 里的某个 Poster(回复人) 名称,怎么找出这个 Poster 回答过的所有 Question?



string poster = "John";
var result = context.Question.AsQueryable();

result = result.Where(p=>p.?); // 这里面该怎么写呢?



如上,谢谢各位~!
...全文
567 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
都不错,赫赫
q107770540 2012-09-23
  • 打赏
  • 举报
回复

1. result = result.Where(p=>p.Answers.Any(x=>x.Id==answerId));

2. result = result.Where(p=>p.Answers.Any(x=>answerIds.Contains(x.Id)));

3.
result=from q in context.Question.AsQueryable()
join a in context.Answer.AsQueryable()
on q.Id equals a.QuestionId
where a.Poster==poster
select q;

davidtsui 2012-09-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
context.Question.Where(x => x.Id == context.Answer.Single(y => y.id == answerId))

answerIds.Select(x => context.Answer.Single(y => y.id == x)).Select(x => context.Question.Single(y => y.id == x.Que……
[/Quote]

1 楼的答案让我叹为观止。
devmiao 2012-09-23
  • 打赏
  • 举报
回复
第三个给的数据结构不全,大致只是个思路,另外两个很简单的,你参考下。
devmiao 2012-09-23
  • 打赏
  • 举报
回复
context.Question.Where(x => x.Id == context.Answer.Single(y => y.id == answerId))

answerIds.Select(x => context.Answer.Single(y => y.id == x)).Select(x => context.Question.Single(y => y.id == x.QuestionId)).Distinct()

context.Question.SelectManay(x => x.Poster.Where(y => y.id == x.poster))

109,897

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧