我有两个关联的实体,关系如下: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.?); // 这里面该怎么写呢?如上,谢谢各位~!
{
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.?); // 这里面该怎么写呢?如上,谢谢各位~!
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;