【问题标题】:How to make a query with the filter in a generic list?如何使用通用列表中的过滤器进行查询?
【发布时间】:2018-09-11 20:21:31
【问题描述】:

我有通用对象T

我想像在 SQL 中使用逻辑运算符或"OR column1 = 123""OR column2 = 123" 一样进行查询以通知属性

public ActionResult Result<T>(HttpContext httpContext, IQueryable<T> queryable, string[] columns = null)
{
    var entity = queryable;
    string searchValue = "123";

    if (!string.IsNullOrEmpty(searchValue))
    {
        entity = entity.Where(""); // columns              
        ...
    }
}

【问题讨论】:

  • 如果你试图访问 specific 类型的属性,不要使用泛型(当你需要访问特定的东西时,它显然不是泛型的)。使您的参数成为该类型并一起抛弃泛型,或者如果您必须使用泛型,请确保使用where T: someType 限制该类型。除非我误会了
  • @JesusPocoata,是的。如何使这个动态?

标签: c# entity-framework lambda ef-core-2.1


【解决方案1】:

您可以应用接口约束,但老实说,如果我是您,我会尽快不这样做,因为它可能导致代码更难以阅读和维护。

public interface ICommonEntity
{
    string Column1 { get; }
    string Column2 { get; }
}

使任何适用的类型实现上述接口

public ActionResult Result<T>(HttpContext httpContext, IQueryable<T> queryable, string[] columns = null) where T : class, ICommonEntity
{
    var entity = queryable;
    string searchValue = "123";

    if (!string.IsNullOrEmpty(searchValue))
    {
        entity = entity.Where(_ => _.Column1 == searchValue || _.Column2 == searchValue);
        ...
    }
}

【讨论】:

    【解决方案2】:

    如果你有实体

    class Foo {
        public string BazFoo { get; set; }
    }
    
    class Bar {
        public string BazBar { get; set; }
    }
    

    你可以创建一个接口:

    public interface IBaz
    {
        string GetBaz();
    }
    

    并由您的实体实施:

    class Foo : IBaz
    {
        public string BazFoo { get; set; }
        public string GetBaz() => BazFoo;
    }
    
    class Bar : IBaz
    {
        public string BazBar { get; set; }
        public string GetBaz() => BazBar;
    }
    

    您可以通过以下方式使用它:

    if (!string.IsNullOrEmpty(searchValue))
    {
        entity = queryable.Where(_ => _.GetBaz() == searchValue);
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-23
      • 2021-01-11
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多