【问题标题】:Does not contain a definition for 'ProjectTo'不包含“ProjectTo”的定义
【发布时间】:2021-10-26 08:11:21
【问题描述】:

我正在尝试将 automapper 与通用存储库一起使用,但出现以下错误:

'Task<IEnumerable<Category>>' does not contain a definition for 'ProjectTo' and the best extension method overload 'Extensions.ProjectTo<IEnumerable<CategoryResponse>>(IQueryable, IConfigurationProvider, params Expression<Func<IEnumerable<CategoryResponse>, object>>[])' requires a receiver of type 'IQueryable'

这是在存储库中

    public async Task<IEnumerable<TEntity>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

这是在控制器中

    public async Task<IActionResult> GetCategories()
    {
        var c = await _unitOfWork.CategoryRepositoryAsync.GetAllAsync()
            .ProjectTo<IEnumerable<CategoryResponse>>(_mapper.ConfigurationProvider);

        return Ok(c);
    }

我是全新的 netcore,而且自动映射器不像我以前使用的那样。我确信这是一个愚蠢的问题,但请坦白我的学习过程。

【问题讨论】:

  • 你试过(await _unitOfWork.CategoryRepositoryAsync.GetAllAsync()).ProjectTo(...)吗?
  • 我试过了,不行。

标签: .net-core automapper


【解决方案1】:

我通过更改 repo 解决了这个问题

    public async Task<IEnumerable<TEntityProject>> GetAllAsync()
    {
        return await _dbSet.ProjectTo<TEntityProject>(_mapper.ConfigurationProvider).ToListAsync();
    }

我只是不喜欢它,因为我需要向存储库添加另一个泛型,但我想它现在可以工作,只构建 scheleton 和一些 crud 操作。

    public class Repository<TEntity, TEntityProject> : IRepositoryAsync<TEntity, TEntityProject> where TEntity: class
                                                                                             where TEntityProject:class

当然,我必须更改它确实中断的所有内容,其影响是我需要小心我如何根据 POST 或 GET 使用这些泛型类型

控制器代码现在是这样的:

    [HttpGet]
    public async Task<IActionResult> GetCategories()
    {
        var c = await _unitOfWork.CategoryRepositoryAsync.GetAllAsync();

        return Ok(c);
    }

一切正常,问题解决。但我可能会问一些更有经验的网络开发人员,这可以是一个长期的解决方案吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多