如何配置 AutoMapper 将所有引用类型集合转换为整数集合?
假设我有以下实体:
public class Store
{
public List<Product> Products { get; set; }
public List<Employee> Employees { get; set; }
public List<Camera> Cameras { get; set; }
}
换句话说,一个包含 Products
、Employees
和安全 Cameras
的 Store
>。我想将此 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们通过一些 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.