如何进行EF Linq查询,包括相关实体的子集

本文关键字:实体 子集 包括相 何进行 EF Linq 查询 | 更新日期: 2023-09-27 17:57:55

我有以下类:

public class Problem
{
    public Problem()
    {
        this.Questions = new HashSet<Question>();
        this.Solutions = new HashSet<Solution>();
    }
    public int ProblemId { get; set; }
    public string Title { get; set; }
    public string Note { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
    public virtual ICollection<Solution> Solutions { get; set; }
}
public class Question
{
    public int QuestionId { get; set; }
    public int ProblemId { get; set; }
    public int QuestionStatusId { get; set; }
    public string Note { get; set; }
    public virtual Problem Problem { get; set; }
}
public class Solution
{
    public int SolutionId { get; set; }
    public int Number { get; set; }
    public int ProblemId { get; set; }
    public bool? Correct { get; set; }
    public string Text { get; set; }
    public string Note { get; set; }
    public virtual Problem Problem { get; set; }
}

有人能帮我为我的EF6,1 SQL Server 2012使用LINQ吗。

我想做的是得到一个只包含数据子集的列表。在这种情况下,我希望从数据库中提取Problem、Question和Solution Entities中的Notes属性,而不是

请注意,"问题"answers"解决方案"表已连接到"问题"表。我不是100%确定这一点,但我认为这意味着我不需要添加。包括。

理想情况下,我希望EF导致问题的选择不包括Notes列。

如何进行EF Linq查询,包括相关实体的子集

您可以使用EF的表拆分功能。创建Problem(PK+all fields except for Notes)ProblemNotes(PK+Notes)实体。然后查询Problem应该可以满足您的需求。

http://msdn.microsoft.com/en-us/data/jj715645.aspx

通过实体框架表拆分,您可以将可能包含大量数据的属性分离到一个单独的实体中,并仅在需要时加载。

您可以使用.Select(…)来避免从数据库中获取冗余数据。下面的代码说明了如何获取只有ProbemId和Title字段的问题列表:

var result = context.Problems.Select(problem => new { ProblemId = problem.ProblemId , Title = proble.Title }).ToList(); 

使用上面的.Select将生成SQL查询"Select p.ProblemId,p.Title from dbo.Problems as p"。使用.List将检索数据(它将不再依赖于上下文)您可能会将结果集转换为问题类型,例如:

var newResult = result.Select(x=>new Problem() { ProblemId = x.ProblemId, Title = x.Title } )