【问题标题】:How to apply GroupJoin properly with aggregate function?如何使用聚合函数正确应用 GroupJoin?
【发布时间】:2021-07-24 17:45:30
【问题描述】:

我在使用数据库方面有点老派,对 LINQ 不太熟悉。我找到了一个 LINQ 扩展来实现我所需要的,但我坚持正确使用它。我是GroupJoin

我真正需要做的是“每个帖子的类别和该类别的数量”

型号

发布内容

public class PostContent
{
    [Key]
    public Guid Id { get; set; }
    public string title { get; set; }
    public string subTitle { get; set; }
    public string description { get; set; }
    public DateTime postDate { get; set; } = DateTime.Now;
    public string post { get; set; }

    public Guid? postCatId { get; set; }
    [ForeignKey("postCatId")]
    public virtual PostCategory postCategory { get; set; }
}

帖子类别

public class PostCategory
{
    [Key]
    public Guid Id { get; set; }
    public string categoryName { get; set; }

    public virtual List<PostContent> postContents { get; set; }

}

我的尝试“但什么也没返回”

    var NumberOfCategoriesForEachPost = context.postCategories 
    .GroupJoin( context.postContents,
    cat => cat.Id,
    con => con.postCatId, 
    (Category, Content) => new  
    {
        Cate = Category.categoryName,
        Cont = Content.Count()
    });

【问题讨论】:

    标签: sql-server asp.net-mvc entity-framework linq asp.net-core


    【解决方案1】:

    如果您的LINQ 查询未在categoryName 列上指定group byGroupJoin 似乎在加入列上进行分组。 您可以改用 LINQ to SQL,因为我发现它更具可读性:

    var query = from cat context.postCategories
             join con in context.postContents
             on cat.Id equals con.postCatId
             group new {cat, con} by new {cat.categoryName } into g
             select new 
             {
                  g.Key.categoryName ,
                  Count = g.Select(s => s.con.postCatId).Count()
             };
    

    【讨论】:

    • 感谢您的帮助,但它给了我任何尝试。
    【解决方案2】:

    感谢@Nikhil Patil,你启发了我做出正确的决定。

    我找到了正确的方法如下

            var query = from cat in context.postCategories
                        join con in context.postContents
                        on cat.Id equals con.postCatId
                        group new { cat, con } by new { con.postCatId, cat.categoryName } into g
                        select new
                        {
                            //g.Key,
                            CategoryName = g.Key.categoryName,
                            CategoryID = g.Key.postCatId.ToString(),
                            Count = g.Count()
                        };
    

    结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2021-08-16
      • 2017-12-01
      • 1970-01-01
      • 2017-10-11
      • 2011-03-03
      相关资源
      最近更新 更多