简体   繁体   中英

LINQ query using TPH inheritance - get derived class ICollection count

I am trying to figure out how to get the count of ProjectSummaryVotes on a specific ProjectDoc.OfType. The query works but the ProjectSummaryVote attribute is null, which means I get a null value error. Is this doable? Should I abandon TPH inheritance if I need to do this?

Model:

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

Query:

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

Attempt to get the count that throws an error.

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

I remodeled the data so that all of the votes are now part of a single Vote model. That let me move the vote relationship out of the derived model and into the primary model, which then makes accessing the data easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM