gpt4 book ai didi

entity-framework-core - 如何将 ProjectTo 与 Automapper 8.0 依赖注入(inject)一起使用

转载 作者:行者123 更新时间:2023-12-04 11:09:28 25 4
gpt4 key购买 nike

我在我的项目中使用 Automapper (8.0) DI 模式,并希望开始在我的 Entity Framework Core 实体查询中使用 ProjectTo。
这是我设法开始工作的示例:

public async Task<IEnumerable<SomeViewModel>> GetStuffAsync() {

return await _dbContext.SomeEntity
.ProjectTo<SomeViewModel>(_mapper.ConfigurationProvider)
.ToListAsync();
}

上面的调用返回所有预期的记录,但它需要注入(inject) IMapper在存储库的构造函数中以及对 AutoMapper.QueryableExtensions 的 Using 引用。
我发现有两个版本的 AutoMapper 文档,它们似乎提供了相互矛盾的信息。
这些文档 https://automapperdocs.readthedocs.io/en/latest/Dependency-injection.html声明如下:

Using DI is effectively mutually exclusive with using theIQueryable.ProjectTo extension method. UseIEnumerable.Select(_mapper.Map<DestinationType>).ToList() instead.


而这些文档 http://docs.automapper.org/en/stable/Dependency-injection.html声明:

Starting with 8.0 you can use IMapper.ProjectTo. For older versionsyou need to pass the configuration to the extension methodIQueryable.ProjectTo<T>(IConfigurationProvider).


按照第一个文档的示例,我将查询转换为:
public IEnumerable<SomeViewModel> GetStuff() {

return _dbContext.SomeEntity
.Select(_mapper.Map<SomeViewModel>)
.ToList();
}
但是,该方法返回 0 条记录(前一个返回所有记录),并且该方法需要从 Async 转换为同步,因为扩展 Select 不支持 ToListAsync()。显然我错过了一些东西。此外,我不确定这是否是正确的技术,因为第二组文档谈到在 8.0 版中使用 IMapper.ProjectTo 而不将配置传递给扩展方法。我怎么做?

最佳答案

Starting with 8.0 you can use IMapper.ProjectTo


这意味着现在 IMapper接口(interface)有一个方法 ProjectTo (类似于 Map )。所以虽然你仍然需要注入(inject) IMapper (但如果您使用 Map ,则无论如何都需要它,所以没有区别),您不需要 QueryableExtensionsProjectTo扩展方法 - 您只需使用接口(interface)方法(类似于 Map ):
return await _mapper.ProjectTo<SomeViewModel>(dbContext.SomeEntity)
.ToListAsync();

请注意, _mapper.ProjectTo 之间存在根本区别。和 Select(_mapper.Map) - 前者被翻译成SQL并在服务器端执行,而后者导致 client evaluation和需求 Include/ ThenInclude (或延迟加载)才能正常运行。

关于entity-framework-core - 如何将 ProjectTo 与 Automapper 8.0 依赖注入(inject)一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53528967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com