C# Automapper首先映射可投影属性,然后映射其他属性

C# Automapper首先映射可投影属性,然后映射其他属性,c#,entity-framework,orm,automapper,projection,C#,Entity Framework,Orm,Automapper,Projection,我有这样的想法: Mapper.CreateMap<UserProfile, UserDTO>() .ForMember(t => t.UserImage, s => s.MapFrom(x => x.Picture(32))) .ForMember(t => t.Permalink, s => s.MapFrom(x => x.Permalink())); unit.User

我有这样的想法:

        Mapper.CreateMap<UserProfile, UserDTO>()
            .ForMember(t => t.UserImage, s => s.MapFrom(x => x.Picture(32)))
            .ForMember(t => t.Permalink, s => s.MapFrom(x => x.Permalink()));
   unit.UserProfiles.GetAll().Project().To<UserDTO>().First();

我想告诉automapper项目映射除这两个属性之外的所有属性,在查询完成后,以正常方式映射这两个属性,这可行吗?

您在这里问了一个错误的问题。您真的需要问“我的底层查询提供程序如何在queryable完成其工作后将一些投影延迟到其他查询”。这将涉及实体框架需要支持的两步过程。下面是代码,没有AutoMapper:

unit.UserProfiles.Select(profile => new UserDTO {
    Id = profile.Id, // I made these two up
    Name = profile.Name,
    UserImage = profile.Picture(32),
    Permalink = profile.Permalink()
}).First();
EF将如何解释这一点?我想不太好。可能是个例外。如果您想在EF中执行此操作,您需要执行以下操作:

LINQ to Entities does not recognize the method 'System.String Picture(xx.xxx.UserProfile, Int32)' method, and this method cannot be translated into a store expression.
unit.UserProfiles.Select(profile => new UserDTO {
    Id = profile.Id, // I made these two up
    Name = profile.Name
    UserImage = profile.UserImage,
    Slug = profile.Slug
}).First();
然后将创建图片的逻辑作为UserDTO的一部分

或者,您只需让用户退出,然后映射即可。这里的关键是AutoMapper只创建一个Select投影,由底层查询提供者来适当地处理它。AutoMapper无法猜测支持或不支持什么,也无法知道如何解析源类型上的自定义方法,以及需要从SQL中获取哪些数据


首先询问-我如何在EF中选择投影来实现这一点?然后AutoMapper将负责封装该投影。

感谢您的回复,我知道EF将无法解释它,我不想让EF这么做,我也知道AutoMapper只创建投影。我想知道我是否可以告诉AM为一些属性创建选择投影,而对于其他属性,我可以告诉AM不要投影它们,而是在查询完成并且我们有了对象之后映射它们。我可以在DTO上实现这些方法,并在getter中调用它们,我只是好奇,顺便说一句,很棒的库。想想看——AutoMapper怎么知道告诉EF哪些属性也需要返回?记住LINQ投影的要点是改变SQL查询。我如何知道在原始SQL查询中包含什么,然后以某种方式保留它(记住,原始源对象永远不会被ORM破坏),在源对象上调用一个不存在的方法,然后映射它?您正在描述一个场景,其中LINQ投影是不可能的。