简体   繁体   English

包含表上的实体框架分组

[英]Entity Framework group by on the included table

I've two tables joined in 1-n way.我有两个表以 1-n 方式加入。

First Table - Users :第一个表 -用户

在此处输入图像描述

Second Table - Consent :第二张表 -同意

在此处输入图像描述

In SQL Server i use this query在 SQL 服务器中,我使用此查询

SELECT *
FROM Users
  Inner Join (
    Select Consent.IDUser, Consent.Type, Consent.Date, Consent.Consent
    From Consent
    Inner Join (
        Select IDUser, Type, Max(Date) as MaxDate
        From Consent
        Group By IDUser, Type
    ) As ConsentGrouped on Consent.IDUser = ConsentGrouped.IDUser and Consent.Type = ConsentGrouped.Type and Consent.Date = ConsentGrouped.MaxDate
  ) as AllData
  On Users.id = AllData.IDUser

to achieve this为达到这个

在此处输入图像描述

In my .NET project i use entity framework, so i've this two entities:在我的 .NET 项目中,我使用实体框架,所以我有这两个实体:

    public partial class Users
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Users()
        {
            this.Consent = new HashSet<Consent>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Consent> Consent{ get; set; }
    }

public partial class Consent
{
    public int Id { get; set; }
    public Nullable<int> IDUser { get; set; }
    public string Type { get; set; }
    public string Origin { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<bool> Consent { get; set; }

    public virtual Users Users { get; set; }
}

How can i obtain the same query result via Entity Framework?如何通过实体框架获得相同的查询结果? So only the most recent consent by type for each user.因此,只有每个用户的最新同意类型。

I use this lambda to get the user, how can I modify it to obtain the desired result?我用这个 lambda 来获取用户,如何修改它以获得想要的结果?

 var user = await db.Users
     .Include(ut => ut.Consent)
     .Where(ut => ut.Id == userID)
     .FirstOrDefaultAsync();

Thanks!谢谢!

Here I used LINQ instead of lambda expressions because in this scenario lambda can be tricky sometimes, I also used explicit join so the explanation got easier to understand.这里我使用了 LINQ 而不是 lambda 表达式,因为在这种情况下 lambda 有时会很棘手,我也使用了显式连接,因此解释更容易理解。

var query = (from user in users
                    join consent in consents
                        on user.Id equals consent.IdUser
                    group new {user, consent} by new {consent.Type, consent.IdUser} into g 
                    select new { 
                            g.FirstOrDefault().user.Id, 
                            g.FirstOrDefault().user.Name,
                            g.FirstOrDefault().user.SureName,
                            ConsentId = g.FirstOrDefault().consent.Id,
                            g.FirstOrDefault().consent.IdUser,
                            g.FirstOrDefault().consent.Type,
                            g.FirstOrDefault().consent.Origin,
                            Date = g.Max(m => m.consent.Date),
                            g.FirstOrDefault().consent.ConsentFlag
                        }).ToList();

After some tests and several researches, I managed to solve using a complex lambda.经过一些测试和研究,我设法使用复杂的 lambda 解决了问题。

var user = db.Users
    .Where(ut => ut.Id == userID)
    .Select(b => new UsersResource
        {
            Id = b.Id,
            Name = b.Name,
            Surname = b.Surname,
            Consent = b.Consent
            .GroupBy(item => item.Type,
                (key, g) => g.OrderByDescending(gx => gx.Date).FirstOrDefault())
            .Select(st => new ConsentResource
                {
                    Id = st.Id,
                    IDUser = st.IDUser,
                    Type = st.Type,
                    Origin = st.Origin,
                    Date = st.Date,
                    Consent = st.Consent
                }).ToList()
             }).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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