c# - 在 N 层应用程序中使用 DTO 时的 OrderBy

标签 c# entity-framework sorting architecture dto

我有一个用 C# 编写的分层应用程序 -

Front end - (Get pages of Customers)

Business - (CustomerService and Customer class)

DataContracts - (CustomerDTO)

DataAccess - (UnitOfWork and Repositories)

数据库有一个包含一百多个列(很多是冗余的)的 Customer 表,所以我使用 DTO 在业务层填充 Customer 对象。在 Customer 类中,我也从数据库名称中更改了许多字段的名称,例如ID 到 CustomerID,FName 到 Firstname。

前端使用业务层的服务来获取客户,例如GetAll(), GetByID(int customerID).

我还想提供如下所示的 GetPaged 方法

客户服务类

public IEnumerable<Customer> GetPaged(
               Func<IQueryable<Customer>, IOrderedQueryable<Customer>> orderBy, 
               int skip, 
               int take)
{
     foreach (var customerDTO in 
                     unitOfWork.CustomerRepository.GetPaged(orderBy, skip, take))
     {
          yield return new Customer(customerDTO);
     }
}

但这不会起作用,因为 CustomerRepository 需要一个基于 CustomerDTO 而不是 CustomerorderBy .

我不想让前端知道关于 CustomerDTO 的任何信息。

我怎样才能做到这一点?

最佳答案

您可以公开一个包含可用订单选项的 enum,然后在 GetPaged 中您只需根据收到的枚举值创建 OrderBy。

可能的实现可能是:

public enum OrderCustomersBy
{
    FirstNameAsc, FirstNameDesc, AgeAsc, AgeDesc
}

在客户服务中:

private IOrderedQueryable<CustomerDTO> GetOrderBy(OrderCustomersBy orderOption)
{
    IOrderedQueryable<CustomerDTO> orderBy = null;

    switch (orderOption)
    {
        case OrderCustomersBy.FirstNameAsc: 
            // Create order by...
            break;
        case OrderCustomersBy.FirstNameDesc: 
            // Create order by...
            break;
        case OrderCustomersBy.AgeAsc: 
            // Create order by...
            break;
        case OrderCustomersBy.AgeDesc: 
            // Create order by...
            break;
        default:
            throw new NotImplementedException("Order option not implemented: " + orderOption.ToString());
    }

    return orderBy;
}

public IEnumerable<Customer> GetPaged(Func<IQueryable<Customer>> func, OrderCustomersBy orderOption, int skip, int take)
{
    IOrderedQueryable<CustomerDTO> orderBy = this.GetOrderBy(orderOption);

    foreach (var customerDTO in unitOfWork.CustomerRepository.GetPaged(orderBy, skip, take))
    {
        yield return new Customer(customerDTO);
    }
}

关于c# - 在 N 层应用程序中使用 DTO 时的 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988357/

相关文章:

c# - Entity Framework 使用模型与 sqlce 和 sql server/sql express 数据库

c++ - 按键排序 std::unordered_map

c - 按降序对堆栈进行排序

c# - 如何以编程方式区分 epub 固定布局和可重排布局

c# - 无法将数据设置到列表中然后打印。

c# - 使用字节作为主键数据类型

excel - 对字母数字值进行排序

c# - round(microtime(true) * 1000) 等价于 C#

c# - ASPNetCore - 通过 REST 上传文件

c# - 转换为值类型 'Double' 失败,因为具体化值为 null