gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:40 25 4
gpt4 key购买 nike

我有这样的东西:

        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 投影映射除这两个之外的每个属性,并且在完成查询后以正常方式映射这两个属性是否可行?

最佳答案

你在这里问错了问题。你真的需要问“我的底层查询提供者如何将一些投影推迟到可查询完成它的工作之后”。这将涉及 Entity Framework 需要支持的两步过程。这是代码,没有 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 将如何解释这一点?不太好,我想。大概是个异常(exception)。如果您想在 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 中的 Select 投影来完成此操作?然后 AutoMapper 将负责封装该投影。

关于c# - Automapper 首先映射 EF 可投影属性,然后映射其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361093/

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