如何在运行时为EF Core查询选择不同的过滤条件

时间:2020-07-20 14:46:29

标签: entity-framework-core

我有一个查询,该查询基于DB数据计算统计信息。
现在,我想支持向其传递时间范围,但现在的解决方案看起来像个黑客。

public class User
{
    public int Id { get; set; }
    public string Username { get; set; }
    public ICollection<Login> Logins { get; set; }
}

public class UserLogin
{
    public int Id { get; set; }
    public DateTime Created { get; set; }
    //0 means fail, 1 means success
    public int Result { get; set; }
    public int UserId { get; set; }
}


var cutoffDate = request.From ?? DateTime.UtcNow.AddYears(-3);

var loginStats = await context.Set<User>()
                    .Where(a => logins.Contains(a.Login))
                    .Select(u => new
                    {
                        key = u.Username,
                        lastSuccessfulLogin = u.Logins.Where(l => l.Created > cutoffDate && b.Result == 1).Max(bo => bo.Created),
                        lastFailedLogin = u.Logins.Where(l => l.Created > cutoffDate && b.Result == 0).Max(bo => bo.Created),
                    }).ToDictionaryAsync(x => x.key, x => x, cancellationToken);

有人可以建议一种更清洁的方法(没有硬编码的日期)吗?我用表达式树尝试了几种技巧,但是它们不能编译

1 个答案:

答案 0 :(得分:0)

最终我选择了这个版本:

var loginStats = await context.Set<User>()
                .Where(a => logins.Contains(a.Login))
                .Select(u => new
                {
                    key = u.Username,
                    lastSuccessfulLogin = u.Logins.Where(l => (request.From.HasValue && l.Created > request.From) && b.Result == 1).Max(bo => bo.Created),
                    lastFailedLogin = u.Logins.Where(l => (request.From.HasValue && l.Created > request.From) && b.Result == 0).Max(bo => bo.Created),
                }).ToDictionaryAsync(x => x.key, x => x, cancellationToken);

它消除了我以前遇到的有问题的后备(DateTime.UtcNow.AddYears(-3)