简体   繁体   English

通常将IQueryable列表转换为dto对象的列表

[英]Generically convert IQueryable list to a list of dto objects

Background 背景

I have an extension method that converts a list of IQueryable<> to an IEnumerable<>: 我有一个扩展方法,可将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;
}

The item.ToDto extension does this: 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,
    };
}

The question 问题

Is there a way to configure the following so that item.ToDto() works? 有没有一种方法可以配置以下内容,以便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;
}

As is, it doesn't work because .ToDto is an unresolvable symbol for item . .ToDto ,它不起作用,因为.ToDtoitem无法解析的符号。

The problem (as you may know) is how to "generically" map a T to a T2 ? 问题(您可能知道)是如何“一般”地将T映射到T2

You can either use a tool like AutoMapper that you can configure to map generically between any two types, or you can add a parameter for a mapping function: 您可以使用诸如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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM