如何使用LINQ和实体框架6进行表连接?

时间:2014-08-21 11:35:03

标签: c# sql asp.net linq entity-framework

我有三张桌子:考试>目的> ObjectiveDetails

这是他们的样子:

public class Exam
{
    public Exam()
    {
        this.Objectives = new HashSet<Objective>();
    }
    public int ExamId { get; set; }
    public int SubjectId { get; set; }
    public virtual ICollection<Objective> Objectives { get; set; }
}

public class Objective : AuditableTable
{
    public Objective()
    {
        this.ObjectiveDetails = new HashSet<ObjectiveDetail>();
    }
    public int ObjectiveId { get; set; }
    public int ExamId { get; set; }
    public int Number { get; set; }
    public virtual Exam Exam { get; set; }
    public virtual ICollection<ObjectiveDetail> ObjectiveDetails { get; set; }

}

public partial class ObjectiveDetail
{
    public int ObjectiveDetailId { get; set; }
    public int ObjectiveId { get; set; }
    public int Number { get; set; }
    public string Text { get; set; }
    public virtual Objective Objective { get; set; }
}

我应该从这样的考试开始:

 var result = await db.Exams
                      .Where(e => e.Name == name)

或者像ObjectiveDetails这样:

 var result = db.ObjectiveDetails .. ??

如何获得一个对象,显示给定考试的目标和客观详情 ?我应该从db.Exams开始还是应该从db.ObjectiveDetails开始?我只需要做一个连接(如果只在关系世界中)。但是对于LINQ,我不知道从哪里开始。

4 个答案:

答案 0 :(得分:5)

这是我通常在加入两张或更多张桌子时所做的事情,不知道这是不是你想要的:

var info = from p in db.Exam 
           join q in db.objective on p.objectiveid equals q.id
           join r in db.objectivedetails on q.objectivedeailsId equals r.id
           select new
                       {
                           ExamId  = p.ExamId 
                           SubjectId= p.SubjectId
                           ObjectiveId= q.ObjectiveId
                           Number = q.Number
                           ObjectiveDetailId = r.ObjectiveDetailId
                           Text = r.Text
                       } into x
           select x;

答案 1 :(得分:1)

假设实体框架已正确连接您的实体之间的关系,以下内容应返回单个考试以及相关的目标和详细信息: -

var query = db.Exams.Include(e => e.Objectives.Select(o => o.ObjectiveDetails));

var examEntity = query.SingleOrDefault(e => e.ExamId == targetExamId);

上述查询将在幕后使用外部加入,因此即使没有关联的目标/详细信息,也会始终返回(如果找到)考试。如果适用,考试将作为单个对象返回,并包含子目标。

或者,以下内容将使用内部连接返回展平结果集: -

var query = from exam in db.Exams
            from objective in exam.Objectives
            from detail in objective.ObjectiveDetails
            select new
            {
                ExamId = exam.ExamId,
                SubjectId = exam.SubjectId
                ObjectiveId = objective.ObjectiveId
                ObjectiveNumber = objective.Number
                DetailId = detail.DetailId
                DetailNumber = detail.Number
                Text = detail.Text
            };

var examDetails = query.Where(e => e.ExamId == targetExamId).ToArray();

明确使用Linq的'join'关键字没有任何问题,但如果EF知道实体的关联方式,通常是不必要的。

答案 2 :(得分:-1)

From e in db.Exam 
join o in objective on e.objectiveid = o.id
join od in objectivedetails on o.objectivedeailsId = od.id
select e

答案 3 :(得分:-1)

这将返回分组选择,键加计数的枚举。最后转换为列表,以便可以在那一刻检索所有数据

 var results = simulacao.Geracao
                .SelectMany(g => g.ObterCarteiras())
                .SelectMany(cg => cg.CarteiraGeneticaInvestimento)
                .SelectMany(cgi => cgi.HistoricoNaoPodeInvestir)
                .GroupBy(hnpi => hnpi.TipoNaoPodeInvestir)
                .Select(g => new { Tag = g.Key, Frequency = g.Count() })
                .ToList();

这与前一个行为相同,但有两种方法可以获得与LINQ相同的信息

var geracoes = (from g in simulacao.Geracao
                        from cg in g.ObterCarteiras()
                        from cgi in cg.CarteiraGeneticaInvestimento
                        from hnpi in cgi.HistoricoNaoPodeInvestir
                        group hnpi by hnpi.TipoNaoPodeInvestir into g
                        select new
                        {
                            TipoNaoPodeInvestir = Utilities.GetEnumDescription((EnumTipoNaoPodeInvestir)g.Key),
                            Count = g.Count()
                        }).ToList();

最后我们可以将列表转换为json结果

return Json(geracoes, JsonRequestBehavior.AllowGet);

请注意,使用“select new”,我们会创建一种新类型的对象,只有两个属性