【问题标题】:How can I do an EF Linq query, including a subset of related entities如何进行 EF Linq 查询,包括相关实体的子集
【发布时间】:2014-04-11 06:53:21
【问题描述】:

我有以下课程:

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; }
}

谁能帮我使用 LINQ 用于我的 EF6,1 SQL Server 2012。

我想做的是得到一个只包含数据子集的列表。在这种情况下,我希望问题、问题和解决方案实体中的 Notes 属性从数据库中获取。

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

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

【问题讨论】:

  • 显示你正在训练做什么?
  • 这是作业吗?你试过什么?
  • 不太清楚你在这里问什么?您只想从Problem 表中选择Notes 列吗?
  • 我想从数据库中获取除 Notes 列之外的所有内容。

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


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢。我现在就去看看。
【解决方案2】:

您可以使用 .Select(...) 来避免从数据库中获取冗余数据。下面的代码说明了如何获取只有 ProblemId 和 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 } )

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多