我只想尝试从两个实体进行连接。
这两个部分如下:public partial class AnswerSet
{
public int Id { get; set; }
public string Ans { get; set; }
public bool IsTrue { get; set; }
public int QuestionId { get; set; }
public virtual QuestionSet QuestionSet { get; set; }
}
和
public partial class QuestionSet
{
public QuestionSet()
{
this.AnswerSets = new HashSet<AnswerSet>();
}
public int Id { get; set; }
public string Quest { get; set; }
public virtual ICollection<AnswerSet> AnswerSets { get; set; }
}
因此,数据库上有一个问题和一个答案实体。 1问题有更多答案(在我的例子4中)。所以现在我尝试了这个:
var v1 = db.QuestionSets
.Select(q => q)
.Where(q=> q.Id == 11)
.Join(db.AnswerSets,
q => q.Id,
a => a.QuestionId,
(a, q) => new { question = q });
所以,现在我的表达式如上所示(见图1):
这里我只有答案。 当我把表达变为:
var v1 = db.QuestionSets
.Select(q => q)
.Where(q=> q.Id == 11)
.Join(db.AnswerSets,
q => q.Id,
a => a.QuestionId,
(q, a) => new { question = q });
然后我有以下输出(见图2):(只是问题,但是4次。我有很多答案。)
所以我的问题是,我如何加入这两个实体,Answers是QuestionSet实体中的一个集合?
谢谢
答案 0 :(得分:2)
您想要群组加入(请参阅http://msdn.microsoft.com/en-us/library/bb311040.aspx)
var QAs =
from q in db.QuestionSets
join a in db.AnswerSets
on q.Id equals a.QuestionId into answers
select new { Question = q, Answers = answers };
在扩展方法语法中:
var QAs = db.QuestionSets
.GroupJoin(
db.AnswerSets,
q => q.Id,
a => a.QuestionId,
(q, answers) => new {Question = q, Answers = answers});
希望有所帮助
PS。像这样使用它:
foreach (var qa in QAs)
{
Console.WriteLine("Question #{0} has {1} answers",
qa.Question.Id, qa.Answers.Count());
}
答案 1 :(得分:0)
如何将Join技术用于复杂查询,并使用Include
使用Ef Eager Loadingvar v1 = db.QuestionSets.Include(b = b.Answer);
或
var v1 = db.QuestionSets.Include("Answer");