据我对这段代码的理解,它从 IQueryable 到 Generic 的映射 (
创建静态类名“Queryablemappingextensions” 还有这个方法
public static IQueryable<TDestination> ProjectTo<TDestination>(this IQueryable source, params Expression<Func<TDestination, object>>[] membersToExpand)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return source.ProjectTo(MappingConfig.Instance.ConfigurationProvider, null,membersToExpand);
}
和
public static IQueryable<TDestination> ProjectTo<TDestination>(
this IQueryable source,
object parameters)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return source.ProjectTo<TDestination>(MappingConfig.Instance.ConfigurationProvider,parameters);
}
我有模型“RoomType”
public class RoomType
{
public int RoomTypeId { get; set; }
public string Type { get; set; }
public string Description { get; set; }
// One-to-many relationship: One RoomType has many Rooms
public virtual ICollection<Room> Rooms { get; set; }
}
我有名为“roomTypeService”的服务 并且有一个获取房间类型并从数据库中检索特定房间类型以获得特定房间类型 ID 的方法
public async Task<T> GetRoomType<T>(int id)
{
return await this._db.RoomTypes
.Where(x => x.RoomTypeId == id)
.ProjectTo<T>()
.FirstOrDefaultAsync();
}
当我调用该方法时,它是这样的
var roomType = await _roomTypeService.GetRoomType<RoomTypeViewModel>(id);
模型 RoomTypeViewModel 与 RoomType 完全相同。
似乎自动映射了 RoomTypeViewModel 的通用。
它可以工作,但我需要知道它到底是如何工作的,以及是否有任何方法可以用另一种比这更容易的方式来做到这一点。
我尝试了可查询扩展 从文档中没有提及此案例。
不确定“更简单”是什么意思,但至于这两种方法的作用在可查询扩展文档的显式扩展部分中有介绍:
在某些场景中,例如 OData,通用 DTO 通过
控制器操作返回。如果没有明确的指示,AutoMapper 将展开结果中的所有成员。要控制投影期间展开哪些成员,请在配置中设置IQueryable
,然后传入要显式展开的成员。ExplicitExpansion
提供的代码使用的策略是使用具有相同名称的扩展方法,并依赖编译器根据参数选择正确的方法(我假设主要目标是跳过在每个地方注入和传递 AutoMapper 的
IConfigurationProvider
的必要性)通过全局实例使用)。