【问题标题】:Excluding the derived classes in the Count funtion in entity framework core排除实体框架核心Count函数中的派生类
【发布时间】:2020-02-07 12:42:03
【问题描述】:

我有以下声明。

 List<ApplicationUserDto> peers = _context.ApplicationUsers
        .Select(m => new ApplicationUserDto
          {
              Id = m.Id,
              MyCount = m.GroupMemberships
                         .Count(pg => pg.StudentGroup.ReviewRoundId == reviewRoundId)
          }).ToList();

我有另一个类,称为PeerStudentGroup,它派生自StudentGroup。在Count() 函数中,我不希望它们被包含在内。我的意思是我只想计算它是否是 StudentGroup 类型(不是从它派生的另一个类)。我想知道我怎么能做到这一点。有什么建议吗?

【问题讨论】:

    标签: c# asp.net entity-framework linq entity-framework-core


    【解决方案1】:

    在这种情况下,您可以使用比较实例类型的is 关键字。您应该将!(pg.StudentGroup is PeerStudentGroup) 添加到您的条件中。

    您的代码应如下所示:

     List<ApplicationUserDto> peers = _context.ApplicationUsers
            .Select(m => new ApplicationUserDto
              {
                  Id = m.Id,
                  MyCount = m.GroupMemberships
                             .Count(pg => pg.StudentGroup.ReviewRoundId == reviewRoundId && !(pg.StudentGroup is PeerStudentGroup))
              }).ToList();
    

    【讨论】:

      【解决方案2】:

      这可能有助于开始:

      在投影(选择)之前应用 .Where(过滤)语句,如

      MyCount = m.GroupMemberships .Where(gm => !(gm is PeerStudentGroup)) [alternatively] typeof(gm) != typeof(PeerStudentGroup) .Count(pg => pg.StudentGroup.ReviewRoundId == reviewRoundId)

      【讨论】:

        猜你喜欢
        • 2021-11-17
        • 2018-07-13
        • 1970-01-01
        • 2019-02-12
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多