将 Linq 查询结果映射到 DTO 类
- 作者: 记忆改变了时间
- 来源: 51数据库
- 2022-12-13
问题描述
我想使用 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
}
}
};
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
