如何使用LinQ To实体从多个表中获取数据行

时间:2017-06-05 14:27:39

标签: entity-framework linq asp.net-mvc-5 entity-framework-6 linq-to-entities

我首先使用dbcontext Code来获取基于此条件的查询,用于下面的类(表):

创作者!= null&& ArticleAttached!= null&& !IsCancelled

var ArticleStudentLiked = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.StudentsLiked.Count);

  var NewsArticleComment = dbcontext.LearningActivites
  .Where(la => la.Creator != null && la.ArticleAttached != null && !la.IsCancelled)
  .Sum(la => la.ArticleAttached.Comments.Count);

以下方法仅返回计数:

  • ArticleStudentLiked
  • ArticleComment

我需要从查询中获取记录行到单个集合中,我可以将其传递给View以逐行显示

像这样:

文章标题,喜欢的数量,评论数量

如何使用LinQ获取这些:文章标题,没有。喜欢,评论的数量

Classes:


 public class LearningActivity
 {
   public virtual ArticleCreator Creator { get; set; }        
   public virtual ArticleCreator EditedBy { get; set; }        
   public virtual Teacher CreatedByTeacher { get; set; }   
   public virtual Article ArticleAttached { get; set; }   
   public virtual Article ArticleAttachedByOther { get; set; } 
   public bool IsCancelled { get; set; }
 }


 public class Article 
 {
   public string ArticleTitle {get;set;}
   public virtual IList<Teacher> TeachersLiked { get; set; }
   public virtual IList<Student> StudentsLiked { get; set; }
   public virtual IList<ArticleComment> Comments { get; set; }
 }


 public class Student
 {
   public virtual IList<ArticleCommentStudent> Comments { get; set; }
 }

由于

1 个答案:

答案 0 :(得分:0)

你能试试吗

// LikeCount is total of Teacher and Student Likes 
// and where clause can be added before Select
var result = dbcontext.Classes
            .Select(x=> new { ArticleTitle = x.ArticleTitle, 
                              LikeCount = x.TeachersLiked.Count() + x.StudentsLiked.Count(), 
                              CommentCount= x.Comments.Count }).First();