简体   繁体   English

使用Automapper投影

[英]Projection with Automapper

I need made a projection from database to model entity. 我需要从数据库到模型实体进行投影。 Before get data in database and map to Entity with unity of word and reposy: 在获取数据库中的数据并将其统一映射到Entity之前,要做到:

 public async Task<IEnumerable<Entity>> GetProjectsSponsorByYear(Guid idUser)
    {
        logger.Trace("Called GetProjectsSponsorByYear method in ProjectBusiness");
        var Entitys = await this.unitOfWork.Repository<Entity>().Queryable().Where(p => p.SponsorId == idUser && p.Draft == true).ToListAsync();


 return listProjectDataBaseAsModel;

, after that use automapper for create a map between Entity and model: ,之后使用automapper在Entity和模型之间创建映射:

this.CreateMap<Entity, Model>()
            .ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.ID))
            .ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))


public async Task<IEnumerable<Model>> GetProjectHistoricList()
    {
        logger.Trace("Called GetProjectHistoricList method in ProjectService");

        var allProjects = await this.projectBusiness.GetAll();

        var allProjectsGrid = this.entityMapper.Map<IEnumerable<Entity>, IEnumerable<Model>>(allProjects);

        return allProjectsGrid;
    }

But now i need made a projection from database to model entity, the problem is when use createMap, for configuration automapper, i have property with method 但是现在我需要从数据库到模型实体进行投影,问题是当使用createMap进行配置自动映射时,我具有方法的属性

 .ForMember(dest => dest.ImpactSupervisorDescription, opt => opt.MapFrom(src => src.ImpactSupervisor.GetDescription()))

when made the projection between repository and model with ProjectTo method a get Exection from Linq. 当使用ProjectTo方法在存储库和模型之间进行投影时,可以从Linq中获取Exection。 I know this exection is for Linq create a query and not implement this method into her. 我知道此执行是为Linq创建查询而不是在她中实现此方法。

Need to know if there is any way to achieve this, either before or after the projection. 需要知道在投影之前或之后是否有任何方法可以实现此目的。

Check out the AutoMapper.EF6 project, it uses another project, DelegateDecompiler, to build out projections based on the method and property contents. 签出AutoMapper.EF6项目,它使用另一个项目DelegateDecompiler根据方法和属性内容来构建投影。 It examines the IL and builds an expression to match that IL to then pass to your queryable provider: 它检查IL并构建一个与该IL匹配的表达式,然后传递给您的可查询提供程序:

https://www.nuget.org/packages/AutoMapper.EF6/ https://www.nuget.org/packages/AutoMapper.EF6/

Then you can project straight from the queryable to list: 然后,您可以直接从可查询对象到列表进行投影:

var allProjectsGrid = await this.projectBusiness.GetAll()
                                .ProjectToListAsync<Model>();

And as a side note, you don't need those ForMember calls for ID and Title, that's the Auto part of AutoMapper :) 另外,您不需要ID和Title的那些ForMember调用,这就是AutoMapper的Auto部分:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM