将Linq查询结果映射到DTO类

use*_*358 9 c# linq linq-to-entities linq-to-sql

我想使用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
}
Run Code Online (Sandbox Code Playgroud)

我的linq查询看起来像这样

var qry = from ent in TableA
          select ent;
Run Code Online (Sandbox Code Playgroud)

在我的映射类中,我遍历查询结果中的项,如下所示:

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

现在,这适用于TableA中的所有字段,它从数据库中显示一条记录,并在TableA_DTO中为TableA中的每个字段设置所需的属性.我还希望在TableA属性字段中的TableB中填充名称为TableB_records的所有匹配记录,并在TableB_DTO中填充TableB_DTO属性中TableC的所有匹配记录,名称为TableC_records

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

谢谢你的时间...

Adu*_*cci 6

我想你的DTO从改变ListIEnumerable比在做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
                    }
            }
    };
Run Code Online (Sandbox Code Playgroud)

  • @Steven - 不正确.它只发送一个查询. (3认同)
  • 在用EF 4.0进行一些测试后,我得出结论你是对的.我很抱歉.这很酷,因为我目前的经验是,与LINQ to SQL相比,EF 4仍然很糟糕.但这是LINQ to SQL显然无法做到的事情(它将执行N + 1个查询). (3认同)