映射的LINQ查询结果,一类DTO [英] Mapping Linq Query results to a DTO class
问题描述
我想使用EF从数据库中记录并分配值一个DTO class.Consider下表中的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
有关各表A记录有TableB中多条记录。对于每一个记录表B中有表C多条记录。
现在我的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
}
现在这适用于所有领域在表A其中,它带来了从数据库中的一个记录,并设置在TableA_DTO所需属性在表表A的每个字段。我也想通过名字TableB_records以及在TableB_DTO从表C的所有匹配的记录TableB_DTO的属性由名称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
感谢您的时间的方式...
Thanks for your time...
推荐答案
我要你的DTO从列表
到的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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!