自动映射首先映射EF可投影属性,然后映射其他属性

时间:2014-03-12 18:48:45

标签: 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.UserProfiles.GetAll().Project().To<UserDTO>().First();

我得到类似的东西:

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.

我想告诉automapper项目映射除了那两个之外的每个属性,并且在查询完成后以正常方式映射这两个属性,它是否可行?

1 个答案:

答案 0 :(得分:2)

你在这里问错了。您真的需要问“我的底层查询提供程序如何在查询执行其工作后将某些投影推迟”。这将涉及实体框架需要支持的两步流程。这是代码,没有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中这样做,你需要做类似的事情:

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将负责封装该投影。

相关问题