[英]How can I do an EF Linq query, including a subset of related entities
我有以下課程:
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幫助我。
我想做的就是獲取僅包含數據子集的List。 在這種情況下,我希望問題,問題和解決方案實體中的Notes屬性不會從數據庫中獲取。
注意問題和解決方案表連接到問題表。 我不太確定這一點,但是我認為這意味着我不需要添加.include。
理想情況下,我希望EF引起的選擇不包括“注釋”列。
您可以使用.Select(...)來避免從db獲取冗余數據。 下面的代碼說明了如何僅使用ProblemId和Title字段來獲取問題列表:
var result = context.Problems.Select(problem => new { ProblemId = problem.ProblemId , Title = proble.Title }).ToList();
使用上面的.Select將生成SQL查詢“ dbo.Problems as p中的SELECT p.ProblemId,p.Title”。 使用.List將檢索數據(它將不再依賴於上下文),您可能將結果集轉換為問題類型,例如:
var newResult = result.Select(x=>new Problem() { ProblemId = x.ProblemId, Title = x.Title } )
您可以使用EF的表拆分功能。 創建一個Problem(PK+all fields except for Notes)
和一個ProblemNotes(PK+Notes)
實體。 然后針對問題查詢應該可以滿足您的需求。
http://msdn.microsoft.com/en-us/data/jj715645.aspx
通過Entity Framework表拆分,您可以將可能包含大量數據的屬性分離到單獨的實體中,並僅在需要時才加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.