简体   繁体   English

Select 中具有多个参数的 EF Core 表达式

[英]EF Core Expression in Select with multiple parameter

So I have a property that I will parse into the Select method.所以我有一个属性,我将解析到Select方法中。 This will work with one parameter but can I make it work with two, and if I can't what would be the approach?这将与一个参数一起工作,但我可以让它与两个参数一起工作吗?如果我不能,那将是什么方法? I am using EF Core 3.1.8.我正在使用 EF Core 3.1.8。 with the SqlServer 3.1.8 package.使用 SqlServer 3.1.8 package。

private static Expression<Func<ClassOne, bool, ClassTwo> Summary
{
  get
  {
    return (p, myBool) => new ClassTwo()
    {
      ListOfItems = p.ListWithMyItems.Where(i => i.Field == myBool)
    }
  }
}

This is my Expression.这是我的表情。 I query with this method.我用这个方法查询。

public async Task<ClassTwo> GetSummaryAsync(bool isAdmin = false)
{
  return await _context
    .DatabaseTable // type of DbSet<ClassOne>
    .Select(Summary) // how do I parse isAdmin to Summary?
    .ToListAsync();
}

So I hope you can see my problem.所以我希望你能看到我的问题。 I want to avoid the where clause in the method because I have at least 10 other methods that use this Expression in different ways and also in my case it would become an nested Where which is not possible which straight querying.我想避免方法中的 where 子句,因为我至少有 10 种其他方法以不同的方式使用此Expression ,而且在我的情况下,它会变成一个嵌套的Where ,这是不可能直接查询的。 I don't want C# to do the work for me, let SQL Server handle that.我不希望 C# 为我完成工作,让 SQL 服务器处理。

Thanks in advance!提前致谢!


EDIT:编辑:

I tried this in the GetSummaryAsync but it is not possible:我在GetSummaryAsync中尝试过,但这是不可能的:

.Select(i => (i, isAdmin))

Define extension method定义扩展方法

public static class Extensions {
    public static IQueryable<ClassTwo> Summary(this IQueryable<ClassOne> one, bool myBool)
    {
        return one.Select(p => new ClassTwo
        {
            ListOfItems = p.ListWithMyItems.Where(i => i.Field == myBool)
        });
    }
}

And use it like this.并像这样使用它。

public async Task<ClassTwo> GetSummaryAsync(bool isAdmin = false)
{
  return await _context
    .DatabaseTable 
    .Summary(isAdmin)
    .ToListAsync();
}

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

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