You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 如何在嵌套集合中按指定日期查询PowerUp对象

实现方案

前置准备

首先需要在DataContext中声明对应实体的DbSet,否则EF Core无法直接操作对应表:

public class DataContext : IdentityDbContext<AppUser>
{
    public DbSet<Hero> Heroes { get; set; }
    public DbSet<PowerUp> PowerUps { get; set; }
    // 原有构造函数和OnModelCreating逻辑保持不变
}

场景1:直接查询所有符合日期条件的PowerUp

不需要关联上层Hero、用户信息的场景,直接操作PowerUp表查询即可:

// 示例筛选条件:2024年1月1日及之后的PowerUp记录
DateTime filterDate = new DateTime(2024, 1, 1);
var matchedPowerUps = await _context.PowerUps
    // 筛选符合日期条件的记录
    .Where(p => p.PowerUpDate >= filterDate)
    // 如果需要关联返回对应的Hero信息可加Include,不需要则省略
    .Include(p => p.Hero)
    .ToListAsync();

场景2:从用户/英雄层级嵌套筛选

如果需要限定查询某个用户下的符合条件的PowerUp,有两种常用写法:

写法1:反向关联查询(推荐)

从PowerUp表反向关联上层用户条件,性能更优:

string currentUserId = "当前登录用户的Id";
DateTime filterDate = new DateTime(2024, 1, 1);
var userMatchedPowerUps = await _context.PowerUps
    .Where(p => p.Hero.AppUserId == currentUserId && p.PowerUpDate >= filterDate)
    .Include(p => p.Hero)
    .ToListAsync();

写法2:正向嵌套筛选

如果需要返回包含符合条件PowerUp的Hero列表,可使用Include过滤(EF Core 5.0及以上版本支持):

string currentUserId = "当前登录用户的Id";
DateTime filterDate = new DateTime(2024, 1, 1);
var herosWithMatchedPowerUps = await _context.Heroes
    .Where(h => h.AppUserId == currentUserId)
    // 仅加载Hero下符合日期条件的PowerUp
    .Include(h => h.PowerUps.Where(p => p.PowerUpDate >= filterDate))
    .ToListAsync();

如果使用的是EF Core 5.0以下版本,可改用投影实现相同效果:

var herosWithMatchedPowerUps = await _context.Heroes
    .Where(h => h.AppUserId == currentUserId)
    .Select(h => new 
    {
        HeroInfo = h,
        MatchedPowerUps = h.PowerUps.Where(p => p.PowerUpDate >= filterDate).ToList()
    })
    .ToListAsync();

内容的提问来源于stack exchange,提问作者AnonyXplorer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:36:06