【问题标题】:Grouping 4 Tables using Linq使用 Linq 对 4 个表进行分组
【发布时间】:2015-11-27 21:45:39
【问题描述】:

我有以下要求:

  • 一个评分可以有零个或多个 RatingPictures
  • 一个评分可以有零个或多个评论
  • 一个评论属于一个用户

这是我目前所拥有的:

from rating in Ratings
where rating.LocationID == 1007
    join ratingpicture in RatingPictures
    on rating.ID equals ratingpicture.RatingID into j3
    from ratingpicture in j3.DefaultIfEmpty()
        join comment in Comments
        on rating.ID equals comment.RatingID into j1
        from comment in j1.DefaultIfEmpty()
            join user in Users
            on comment.UserID equals user.ID into j2
            from user in j2.DefaultIfEmpty()
group new { ratingpicture, comment, user } by rating into g
select new { rating = g.Key, ratingpicture= g.Key, comment = g.ToList() }

【问题讨论】:

  • 您遇到什么错误?你能显示你的实体类的定义吗?
  • 这里的问题是“ratingpicture”列与“rating”的内容相同。此外,我的“评论”栏中有“评级图片”,这对我来说毫无意义。
  • 如果您在实体类中正确建模关系,您就不必使用join
  • 你能给我举个例子吗?

标签: c# linq join linq-group


【解决方案1】:

如果您像这样为实体类建模:

public class Comment
{
    public int CommentId { get; set; }
    public int RatingId { get; set; }
    public virtual Rating Rating { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class User
{
    public int UserId { get; set; }

}

public class Rating
{
    public Rating()
    {
        RatingPictures = new HashSet<RatingPicture>();
        Comments = new HashSet<Comment>();
    }

    public int RatingId { get; set; }
    public virtual ICollection<RatingPicture> RatingPictures { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public int LocationID { get; set; }
}

public class RatingPicture
{
    public int RatingPictureId { get; set; }
    public int RatingId { get; set; }
    public virtual Rating Rating { get; set; }

}

那么你的查询就这么简单:

var query = context.Ratings.Where(r => r.LocationID == 1007)
    .Include(r => r.RatingPictures)
    .Include(r => r.Comments.Select(c => c.User));

var result = query.ToList();

在后台,此查询将被转换为连接查询。但这就是 ORM 的美妙之处,我们可以在更抽象的层次上工作。

查看this reference,了解有关实体框架中的关系和导航属性的更多信息。

【讨论】:

  • 不知道这是可能的。我会试试这个。非常感谢。
  • 最后一个问题:这些类连接到 SQL 服务器。我需要在每个虚拟元素前面添加一个 [NotMapped] 吗?
  • @user1705950,不,你没有。 EF 正确理解这些属性。
  • 谢谢你,Yacoub。你让我的生活更轻松:)
猜你喜欢
  • 2013-09-05
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2016-03-28
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多