LINQ查询使用TPH继承 - 获取派生类ICollection计数

时间:2013-01-11 06:23:31

标签: c# .net entity-framework linq-to-entities

我试图弄清楚如何在特定的ProjectDoc.OfType上获取ProjectSummaryVotes的计数。查询有效,但ProjectSummaryVote属性为null,这意味着我得到一个空值错误。这可行吗?如果我需要这样做,我应该放弃TPH继承吗?

型号:

public class Project
{
    public int ProjectID { get; set; }
    public virtual ICollection<ProjectDoc> ProjectDoc { get; set; }

}
public abstract class ProjectDoc
{
    public int ProjectDocID { get; set; }
    public int ProjectID { get; set; }
    public string DocTitle { get; set; }
    public string Status { get; set; }
    public DateTime DateCreated { get; set; }

    public virtual Project Project { get; set; } 
    public virtual ICollection<Comment> Comment { get; set; }
}

public class Summary : ProjectDoc
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
    public ICollection<ProjectSummaryVote> ProjectSummaryVote { get; set; }
}
public class ProjectSummaryVote
{
    public int ProjectSummaryVoteID { get; set; }
    public int ProjectDocID { get; set; }
    public bool Vote { get; set; }
    public virtual Summary Summary { get; set; }
    public virtual User User { get; set; }
}

查询:

 Project project = db.Projects
          .Include(i => i.User)
          .Include(i => i.ProjectDoc)
          .SingleOrDefault(x => x.ProjectID == id);

尝试获取引发错误的计数。

 var trueCount = Model.ProjectDoc.OfType<Literrater.Models.Summary>()
      .Where(s => s.Status == "Active")
      .SelectMany(v => v.ProjectSummaryVote.Where(s => s.Vote == true))
      .Count();

1 个答案:

答案 0 :(得分:0)

我重新设计了数据,以便所有投票现在都是单个投票模型的一部分。这让我可以将投票关系从派生模型转移到主模型中,从而使得访问数据变得容易。