简体   繁体   English

将DTO列表添加到主DTO

[英]Add a list of DTOs to the master DTO

I have two DTOs: 我有两个DTO:

public class MasterDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<DetailDTO> Details { get; set; }
}

public class DetailDTO
{
    public int Id { get; set; }
    public string DetailName { get; set; }
}

Also, I have a function: 另外,我有一个功能:

using (var context = new Context())
{
    var r = context.MasterData
                   .Select(d => new MasterDTO
                   {
                       Id = d.Id,
                       Name = d.Name,
                   }
}

I need to fill the list of DetailDTOs too and do it in a single request. 我也需要填写DetailDTO列表,并在单个请求中完成。

At this moment, I have to get list of DetailsData data and add it through foreach to the MasterDTO, which, of course causes a lot of requests to the database server. 此刻,我必须获取DetailsData数据列表,并通过foreach将其添加到MasterDTO,这当然会导致对数据库服务器的大量请求。

Is there a better solution? 有更好的解决方案吗?

In your data call, do an eager load on your DetailData. 在您的数据通话中,对您的DetailData进行快速加载。 Example: 例:

var r = context.MasterData.Include("DetailData")

DetailData should be the name of your navigation property attached to your MasterData entity. DetailData应该是附加到MasterData实体的导航属性的名称。

This will cause detail data to be pulled along with your call for MasterData . 这将导致详细数据与对MasterData的调用一起被拉出。

The full call may look something like this: 完整呼叫可能看起来像这样:

using (var context = new Context())
{
    context.LazyLoadingEnabled = false;
    var r = context.MasterData.Include("DetailData")
        .Select(d => new MasterDTO()
        {
            Id = d.Id,
            Name = d.Name,
            Details = d.Details.Select(dt => new DetailDTO()
            {
                Id = dt.Id,
                DetailName = dt.DetailName
            })
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM