问题描述
我想使用 EF 从数据库中获取记录并将值分配给 DTO 类.请考虑以下表格以进行 Linq 查询.
I want to get records from the database using EF and assign the values to a DTO class.Consider the following tables for a Linq query.
表A、表B、表C
对于每个 TableA 记录,TableB 中有多个记录.对于每个 TableB 记录,TableC 中有多个记录.现在我的 DTO 看起来像这样
For each TableA record there are multiple records in TableB. For each TableB record there are multiple records in TableC. Now my DTOs look like this
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 查询看起来像这样
my linq query looks something like this
var qry = from ent in TableA
select ent;
在我的映射类中,我遍历查询结果中的项目,如下所示:
In my mapping class I loop through items in query result like so:
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 填充 TableB 属性字段中 TableB 中的所有匹配记录,并在 TableB_DTO 中填充 TableB_DTO 属性中来自 TableC 的所有匹配记录,名称为 TableC_records
Now this works for all fields in TableA where it brings out one record from the database and sets the required properties in TableA_DTO for each field in the table TableA. I want to also populate all matching records in TableB in the TableA property field by the name TableB_records and also in TableB_DTO all the matching records from TableC in TableB_DTO's property by the name TableC_records
这能做到吗?我需要改变什么?是 linq 查询还是我做映射的方式
Can this be done? What do I need to change? Is it the linq query or the way I do my mapping
感谢您的时间...
推荐答案
我会将您的 DTO 从 List
更改为 IEnumerable
,而不是在 LINQ 查询中执行所有操作.
I would change your DTO from List
to IEnumerable
and than do everything in a LINQ query.
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
}
}
};
这篇关于将 Linq 查询结果映射到 DTO 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!