简体   繁体   中英

Add a list of DTOs to the master DTO

I have two DTOs:

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.

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.

Is there a better solution?

In your data call, do an eager load on your DetailData. Example:

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

DetailData should be the name of your navigation property attached to your MasterData entity.

This will cause detail data to be pulled along with your call for 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
            })
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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