如何配置 AutoMapper 将所有引用类型集合转换为整数集合?

发布于 2024-09-24 12:54:00 字数 970 浏览 7 评论 0 原文

假设我有以下实体:

public class Store
{
    public List<Product> Products { get; set; }
    public List<Employee> Employees { get; set; }
    public List<Camera> Cameras { get; set; }
}

换句话说,一个包含 ProductsEmployees 和安全 CamerasStore >。我想将此 Store 转换为 StoreDTO

public class StoreDTO
{
    public List<int> ProductIds { get; set; }
    public List<int> EmployeeIds { get; set; }
    public List<int> CameraIds { get; set; }
}

换句话说,StoreDTO 将仅具有实体 ID。

现在,我正在使用此代码来设置 AutoMapper:

Mapper.CreateMap<Product, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Employee, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Camera, int>().ConvertUsing(x => x.Id);

如您所见,这是很多样板代码。有没有办法配置 AutoMapper 自动将引用类型的所有集合转换为整数集合?

Let's say I have the following entity:

public class Store
{
    public List<Product> Products { get; set; }
    public List<Employee> Employees { get; set; }
    public List<Camera> Cameras { get; set; }
}

In other words, a Store that has Products, Employees, and security Cameras. I want to convert this Store to a StoreDTO:

public class StoreDTO
{
    public List<int> ProductIds { get; set; }
    public List<int> EmployeeIds { get; set; }
    public List<int> CameraIds { get; set; }
}

In other words, the StoreDTO will only have the entity IDs.

Right now, I'm using this code to set up AutoMapper:

Mapper.CreateMap<Product, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Employee, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Camera, int>().ConvertUsing(x => x.Id);

As you can see, it's a lot of boilerplate code. Is there any way to configure AutoMapper to automatically convert all collections of reference types to collections of integers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

他夏了夏天 2024-10-01 12:54:00

我们通过一些 LINQ 反射来完成此操作。您可以使用 LINQ 查询从 Product、Employee 和 Camera 的某个基类派生的所有类型。接下来,循环调用 CreateMap 和 ConvertUsing 方法的这些类型。

没有类型扫描可言,这就是为什么这样的东西并不真正存在。但根据需要进行自己的类型扫描也不算太糟糕。

We do this with a bit of LINQ over reflection. You can use LINQ to query all types that derive from some base class of Product, Employee and Camera. Next, loop through those types calling the CreateMap and ConvertUsing methods.

There's no type scanning to speak of which is why things like this aren't really there. But it's not too bad to do your own type scanning as needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文