【问题标题】:Convert Entity with navigation property to DTO using IQueryable使用 IQueryable 将具有导航属性的实体转换为 DTO
【发布时间】:2016-03-31 20:24:50
【问题描述】:

假设我有以下实体和 dtos

public class Country
{
    public List<NameLocalized> NamesLocalized;
    public CountryData Data;
}

public class NameLocalized
{
    public string Locale;
    public string Value;
}

public class CountryData
{
    public int Population;
}

public class CountryDto
{
    public String Name;
    public CountryDataDto Data;
}

public class CountryDataDto
{
    public int Population;
}

我需要将 Country 转换为 CountryDto(理想情况下,我想对数据库进行一次查询)。我在 Stackoverflow 上的其他问题中收到的建议很少,现在可以完成任务,但只是部分完成。我被困在如何转换导航属性(在这种情况下为CountryData)。有人建议我为此使用LINQKit,但不知道如何实现它。这是我的代码,它仅填充 Name 属性而不是 Data 导航属性。

public static async Task<List<CountryDto>> ToDtosAsync(this IQueryable<Country> source, string locale)
{
    if(source == null)
    {
        return null;
    }

    var result = await source
        .Select(src => new CountryDto
        {    
           Name = src.NamesLocalized.FirstOrDefault(n => n.Locale == locale).Name
        })
        .ToListAsync();

    return result; 
}

【问题讨论】:

    标签: c# entity-framework linq iqueryable


    【解决方案1】:

    This 回答给了我解决方案的提示。您需要使用 LINQKit 并构建 Expression 来转换导航属性。

    public static Expression<Func<CountryData, CountryDataDto>> ConverterExpression = cd => new CountryDataDto
            {
                Population = cd.Population
            };
    
    public static async Task<List<CountryDto>> ToDtosAsync(this IQueryable<Country> source, string locale)
    {
        if(source == null)
        {
            return null;
        }
    
        var result = await source
            .AsExpandable
            .Select(src => new CountryDto
            {    
               Name = src.NamesLocalized.FirstOrDefault(n => n.Locale == locale).Name
               Data = ConverterExpression.Invoke(src.Data)
            })
            .ToListAsync();
    
        return result; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 2019-04-22
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多