c# - 通用存储库模式和理解语法

标签 c# generics linq-expressions

我一直在看Chris Sakell's博客,尤其是 ASP.Net API 实现。

我对他的通用存储库实现的实际语法有疑问。我希望有人能简单而详细地解释语法以及如何在 Controller 中使用它。

首先,我无法理解以下方法签名:

public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)

这是签名..

  • “表达”是什么意思?
  • 为什么需要创建表达式树
  • “谓词”是什么意思?
  • “includeProperties”是什么意思?

这个签名的方法是:

    public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _context.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query.Where(predicate).FirstOrDefault();
    }

最后,我该如何使用它 - 同时理解“includeProperty”指的是什么?

我一直在努力寻找关于这个特定主题的博客/文章和教程,但难以找到。任何额外的阅读 Material 都将非常感谢专注于上述签名等......

最佳答案

  • 表达式表示代码的任何元素 - 方法、参数、字段、if-else 语句等。

  • Expression API 用作将代码转换为可查询信息的机制。

  • 表达式树是表达式(编程语言语句)的集合。

  • Expression API 非常有用,例如,在与数据存储驱动程序通信或实现数据存储驱动程序时,因为它使驱动程序供应商能够将 C# 代码翻译成数据存储的语言(SQL 就是一个例子) .

  • Predicate 是一个函数,它接受一组非空参数(一个或多个)并返回一个 bool 值。例子:

     
     bool IsBroken(Car car);
     bool IsMildRainExpected(WeatherForecast forecast, int threshold);
    

  • The method in question simply returns the first item from a data store, for which the parameter predicate returns true. It does not necessarily map all of the fields present in the matching object into the returned instance- but instead maps only the values which were specified by the includeProperties expressions.

Consider the following POCO:

class Trump
{
  public int Make {get;set;}
  public string America {get;set;}
  public double Great {get;set;}
  public float Again {get;set;}
}

我们可以选择在数据存储中查询上述类型的实例,前提是它们的“Make”值大于 2016,并且只映射“America”和“Great”属性的值,如下所示:

Trump trump = Single<Trump>(t=>t.Make>2016, t=>t.America, t=>t.Great);

请随时要求任何说明。

关于c# - 通用存储库模式和理解语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702337/

相关文章:

c# - 如何在按钮上显示菜单项单击工具条

class - swift 从泛型类派生的类的限制

c# - 使用 Enum as/with 表达式?

c# - Linq 表达式。相当于大于字符串

java - 从java文件中加载数据

c# - 包含在 C# 中比较字符串数组的方法

c# - ComboBox在下拉时如何捕获鼠标?

c# - 业务对象和数据访问对象之间的存储库模式和映射

c# - 启动 ConfigureServices AddMvc() 中的 KeyNotFoundException

java - Sun Codemodel 泛型方法调用