c# - 将 Linq 查询结果映射到 DTO 类

标签 c# linq linq-to-sql linq-to-entities

我想使用 EF 从数据库中获取记录并将值分配给 DTO 类。考虑下表中的 Linq 查询。

表A,表B,表C

对于每个 TableA 记录,在 TableB 中有多个记录。对于每个 TableB 记录,在 TableC 中有多个记录。 现在我的 DTO 看起来像这样

public class TableA_DTO
{
    public int tableA_rowid { get; set; }
    //remaining tableA field definitions

    public List<TableB_DTO> TableB_records { get; set; }
}

public class TableB_DTO
{
    public int tableB_rowid { get; set; }
    //remaining tableB  field definitions

    public List<TableC_DTO> TableC_records { get; set; }
}

public class TableC_DTO
{
    public int tableC_rowid { get; set; }
    //remaining tableC field definitions
}

我的 linq 查询看起来像这样

var qry = from ent in TableA
          select ent;

在我的映射类中,我像这样遍历查询结果中的项目:

    foreach (var dataitem in query)
    {
        TableA_DTO dto = new TableA_DTO();
        dto.tableA_rowid =  dataitem.ID;
        //remaining field definitions here
    }

现在这适用于 TableA 中的所有字段,它从数据库中提取一条记录,并在 TableA_DTO 中为表 TableA 中的每个字段设置所需的属性。我还想通过名称 TableB_records 在 TableA 属性字段中的 TableB 中填充所有匹配记录,并在 TableB_DTO 中通过名称 TableC_records 在 TableB_DTO 的属性中填充来自 TableC 的所有匹配记录

这能做到吗?我需要改变什么?是 linq 查询还是我做映射的方式

感谢您的宝贵时间...

最佳答案

我会将您的 DTO 从 List 更改为 IEnumerable,然后在 LINQ 查询中执行所有操作。

var query = 
    from ent in TableA
    select new TableA_DTO
    {
        TableAProperty = a.Property,
        TableB_records = 
            from b in TableB
            where ent.Key == b.Key
            select new TableB_DTO
            {
                TableBProperty = b.Property,
                TableC_records =
                    from c in TableC
                    where b.Key == c.Key
                    select new TableC_DTO
                    {
                        TableCProperty = c.Property
                    }
            }
    };

关于c# - 将 Linq 查询结果映射到 DTO 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9333005/

相关文章:

c# - LINQ options.loadwith问题

c# - 如何覆盖 ViewModel DataContext 以便我可以绑定(bind)到 View (Mvvm-Light) 中的对象?

C# 用户名比较(2 个字符串)

C#:如何将对象列表转换为该对象的单个属性列表?

c# - 是否可以使用 LINQ 进行列表操作?

c# - 如何使用linq C#展平列表

C# 定时器和垃圾回收

c# - 服务器的全局文化在不同服务器上不同时的 DateTime 问题

c# - 从通用 List<t> 中删除项目

c# - 如何编写 LINQ to SQL 查询以获取今天的日期记录?