Search code examples
c#entity-frameworkdto

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?


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
                })
            });
    }