Search code examples
c#linqentity-framework-coreautomapperdto

Business Object to DTO conversion


I have a list of types of application. I want to transform that object to an object of type ApplicationDTO. Inside that Application business object, there is a list of Applicants of the type Applicant. Now my DTO has the same list but I am struggling with how to assign the list members of the business object to the list inside the DTO. I have had multiple such occurrences where it is not known how many items I have on the list.
Here is an example:

// List of business objects
List<Application> ApplicationList = await _dbContextDigitVP.Applications.FromSqlRaw("Exec dbo.GetApplication {0}", id).ToListAsync();

//DTO object
ApplicationDTO applicationDTO = new ApplicationDTO
{
    ApplicationNumber = Application.ApplicationNumber,
    Country = Application.Country,
    ApplicationUuid = Application.ApplicationUuid,
    PwEmployeeAdUserName = Application.PwEmployeeAdUserName,
    Category = new ApplicationCategoryDTO
    {
        Category = Application.Category?.Category
    },
    Applicants = new List<ApplicantDTO>()
    {
       // add members of the business object                       
    }

};

I could go over it with a for loop but is there a way to do this inside the object definition?


Solution

  • you can also use LINQ to transform objects like without using AutoMapper.

    List<ApplicationDTO> applicationDTOList = ApplicationList.Select(app => new ApplicationDTO
    {
        ApplicationNumber = app.ApplicationNumber,
        Country = app.Country,
        ApplicationUuid = app.ApplicationUuid,
        PwEmployeeAdUserName = app.PwEmployeeAdUserName,
        Category = new ApplicationCategoryDTO
        {
            Category = app.Category?.Category
        },
        Applicants = app.Applicants.Select(a => new ApplicantDTO
        {
            // same logic as the above
        }).ToList()
    }).ToList();