将IQueryable列表一般转换为dto对象的列表

本文关键字:列表 dto 对象 IQueryable 转换 | 更新日期: 2023-09-27 18:29:45

背景

我有一个扩展方法,用于转换IQueryable列表<>到IEnumerable<>:

public static IEnumerable<PersonDto> ToDtoList(
    this IQueryable<Person> source)
{
    var result = new List<PersonDto>();
    foreach (var item in source)
    {
        result.Add(item.ToDto());
    }
    return result;
}

item.ToDto扩展可以执行以下操作:

public static PersonDto ToDto(this Person source)
{
    if (source == null)
        return null;
    return new PersonDto
    {
        PersonId = source.personId,
        Firstname = source.firstname,
        Lastname = source.lastname,
        DateOfBirth = source.dateOfBirth,
        CreateDate = source.createDate,
        ModifyDate = source.modifyDate,
    };
}

问题

有没有办法配置以下内容以使item.ToDto()工作?

public static IEnumerable<T2> ToDtoList<T, T2>(this IQueryable<T> source)
{
    var result = new List<T2>();
    foreach (var item in source)
    {
        result.Add(item.ToDto());
    }
    return result;
}

照原样,它不起作用,因为.ToDtoitem的不可解符号。

将IQueryable列表一般转换为dto对象的列表

问题(正如您所知)是如何"一般地"将T映射到T2

您可以使用像AutoMapper这样的工具,可以将其配置为在任意两种类型之间进行一般映射,也可以为映射函数添加一个参数:

public static IEnumerable<T2> ToDtoList<T, T2>(this IQueryable<T> source, Func<T, T2> map)
{
    var result = source.AsEnumerable()  // to avoid projecting the map into the query
                       .Select(s => map(s));
    return result;
}