【问题标题】:How to get rows of Data from Multiple Tables using LinQ To Entities如何使用 LinQ To Entities 从多个表中获取数据行
【发布时间】:2017-11-06 08:42:27
【问题描述】:

我首先使用 dbcontext 代码来获取基于此条件的以下类(表)的查询:

Creator != 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);

以下方法仅返回计数:

  • 文章学生喜欢
  • 文章评论

我需要将查询中的记录行放入一个集合中,我可以将其传递给 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; }
 }

谢谢

【问题讨论】:

  • 你想合并哪些类?
  • 类是表,它们是链接的。我需要这样做:获取第一篇文章,然后为这篇文章总结所有的赞和cmets。如何在 LinQ to Entities 中使用?
  • 您的文章是否具有类 ID 属性。在where子句中实现条件
  • 我的回答有用吗?

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


【解决方案1】:

你可以试试这个

// 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();

【讨论】:

  • 嗨,它应该可以工作。我认为您的解决方案应该有效。我把问题分成两部分。现在我得到了第一部分,因为我试图了解如何获取数据。我需要从其他表中获取数据以形成一个集合。但我不知道如何将其链接到第二部分。稍后我会给你链接。
  • 这里是链接stackoverflow.com/questions/44407217/… 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多