使用IQueryable将具有导航属性的实体转换为DTO [英] Convert Entity with navigation property to DTO using IQueryable

查看:485
本文介绍了使用IQueryable将具有导航属性的实体转换为DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下实体和dtos

Suppose I have following entities and 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 进行此操作,但不知道如何实现它。这是我的代码仅填充名称属性,但不包含数据导航属性。

I need to convert Country to CountryDto (and ideally, I want to make a single query to the database). I have received few suggestions in my other questions on Stackoverflow, and can now accomplish the task, but only partially. I am stuck at how to convert navigation property (CountryData in this case). I was suggested to use LINQKit for this, but have no idea how to implement it. Here is my code which populates only Name property but not Data navigation property.

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; 
}


推荐答案

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

This answer gave me the hint for my solution. You need to use LINQKit and build Expression to convert the navigation property.

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; 
}

这篇关于使用IQueryable将具有导航属性的实体转换为DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆