Converting Entity to DTO along with child entities

how to convert dto to entity in spring boot
modelmapper
entity to dto conversion for a spring rest api
conversion entity to dto using modelmapper
java dto best practices
convert list of entity to list of dto
dto class
android model mapper

Trying to convert an entity object to local object so i can use it for further transformations.

Here is the code that i am using to convert the entity object;

IEnumerable<SystemArea> result = (from sa in CurrentContext.systemarea                                 
                                 select new SystemArea
                                 {
                                     SystemAreaId = sa.SystemAreaId,
                                     SystemAreaCode = sa.SystemAreaCode,
                                     SystemAreaType = sa.SystemAreaType,
                                     SystemAreaDescription = sa.SystemAreaDescription,
                                     SystemAreaCreatedDate = sa.SystemAreaCreatedDate,
                                     SystemAreaUpdateDate = sa.SystemAreaUpdateDate,
                                     SystemAreaStatus = sa.SystemAreaStatus,
                                     Count = sa.systemareafunctionality.Count,
                                     SystemAreaFunctionality = sa.systemareafunctionality.Select(e => new SystemAreaFunctionality { SystemAreaCode =e.SystemAreaCode })
                                 }).ToList();

Here the count variable is to confirm whether there is any child data in it.

SystemAreaFunctionality is the child object that i am trying to convert here by using SELECT function but it is always blank collection. Rest data is getting assigned to parent object but the only thing missing here is the child table records. Where am i going wrong, please help!

Generated SQL :

SELECT
`Project3`.`C1`, 
`Project3`.`SystemAreaId`, 
`Project3`.`SystemAreaCode`, 
`Project3`.`SystemAreaType`, 
`Project3`.`SystemAreaDescription`, 
`Project3`.`SystemAreaCreatedDate`, 
`Project3`.`SystemAreaUpdateDate`, 
`Project3`.`SystemAreaStatus`, 
`Project3`.`C3` AS `C2`, 
`Project3`.`C2` AS `C3`, 
`Project3`.`SystemAreaCode1`
FROM (SELECT
`Project1`.`SystemAreaId`, 
`Project1`.`SystemAreaCode`, 
`Project1`.`SystemAreaType`, 
`Project1`.`SystemAreaDescription`, 
`Project1`.`SystemAreaCreatedDate`, 
`Project1`.`SystemAreaUpdateDate`, 
`Project1`.`SystemAreaStatus`, 
1 AS `C1`, 
`Project2`.`SystemAreaCode` AS `SystemAreaCode1`, 
`Project2`.`C1` AS `C2`, 
`Project1`.`C1` AS `C3`
FROM (SELECT
`Extent1`.`SystemAreaId`, 
`Extent1`.`SystemAreaCode`, 
`Extent1`.`SystemAreaType`, 
`Extent1`.`SystemAreaDescription`, 
`Extent1`.`SystemAreaCreatedDate`, 
`Extent1`.`SystemAreaUpdateDate`, 
`Extent1`.`SystemAreaStatus`, 
(SELECT
COUNT(1) AS `A1`
FROM `systemareafunctionality` AS `Extent2`
 WHERE `Extent1`.`SystemAreaCode` = `Extent2`.`SystemAreaCode`) AS `C1`
FROM `systemarea` AS `Extent1`) AS `Project1` LEFT OUTER JOIN (SELECT
`Extent3`.`SystemAreaCode`, 
1 AS `C1`
FROM `systemareafunctionality` AS `Extent3`) AS `Project2` ON `Project1`.`SystemAreaCode` = `Project2`.`SystemAreaCode`) AS `Project3`
 ORDER BY 
`Project3`.`SystemAreaCode` ASC, 
`Project3`.`C2` ASC

JSON output:

[{"SystemAreaId":1,"SystemAreaCode":"KIO","SystemAreaType":"KIOSK","SystemAreaDescription":"tasks related to receptionist","SystemAreaCreatedDate":"/Date(1543421018000)/","SystemAreaUpdateDate":"/Date(1543421018000)/","SystemAreaStatus":true,"SystemAreaFunctionality":[],"Count":1}]

PS : Please don't suggest automapper or extension methods. Thanks!

Use this:

CurrentContext.systemarea.Include('systemareafunctionality')

or

IEnumerable<SystemArea> result = (from sa in CurrentContext.systemarea    
                             join systemareafunctionality in CurrentContext.systemareafunctionality on sa.systemareafunctionalityID equals systemareafunctionality.ID
                             select new SystemArea
                             {
                                 SystemAreaId = sa.SystemAreaId,
                                 SystemAreaCode = sa.SystemAreaCode,
                                 SystemAreaType = sa.SystemAreaType,
                                 SystemAreaDescription = sa.SystemAreaDescription,
                                 SystemAreaCreatedDate = sa.SystemAreaCreatedDate,
                                 SystemAreaUpdateDate = sa.SystemAreaUpdateDate,
                                 SystemAreaStatus = SystemAreaStatus,
                                 Count = systemareafunctionality.Count,
                                 SystemAreaFunctionality = systemareafunctionality.Select(e => new SystemAreaFunctionality { SystemAreaCode =e.SystemAreaCode })
                             }).ToList();

or

IEnumerable<SystemArea> result = (from sa in CurrentContext.systemarea    
                         join systemareafunctionality in CurrentContext.systemareafunctionality on sa.systemareafunctionalityID equals systemareafunctionality.ID into item1 from subitem1 in item1.DefaultIfEmpty() 
                         select new SystemArea
                         {
                             SystemAreaId = sa.SystemAreaId,
                             SystemAreaCode = sa.SystemAreaCode,
                             SystemAreaType = sa.SystemAreaType,
                             SystemAreaDescription = sa.SystemAreaDescription,
                             SystemAreaCreatedDate = sa.SystemAreaCreatedDate,
                             SystemAreaUpdateDate = sa.SystemAreaUpdateDate,
                             SystemAreaStatus = SystemAreaStatus,
                             Count = systemareafunctionality.Count,
                             SystemAreaFunctionality = systemareafunctionality.Select(e => new SystemAreaFunctionality { SystemAreaCode =e.SystemAreaCode })
                         }).ToList();

Converting entity to dto in java, but model mapper maps direct entity to dto properties.it cannot map the child tables data to dto. You can use ModelMapper. It maps the child  Here the count variable is to confirm whether there is any child data in it. SystemAreaFunctionality is the child object that i am trying to convert here by using SELECT function but it is always blank collection. Rest data is getting assigned to parent object but the only thing missing here is the child table records.

Mapping Children with ModelMapper – Amy's Programming Corner, If you want to follow along, use the Spring Initialzr and create a Gradle, Java Entities. The example uses two entity classes to model the So our first converter is going to cover mapping from the DTO to the entity object. Well for me I like my controllers clean and tidy, so I made sure that all my services return a DTO and never an entity. So after doing what needs to be done in a service method, I would convert the entity object and return a DTO 🙂 It really looks clean. Also I created a conversion service bean that has many methods for different DTO conversions.

Apparently your CurrentContext is a Dbcontext with at least a table of SystemAreas and a table of SystemAreaFunctionalities.

It seems that every SystemArea has zero or more SystemAreaFunctionalities; every SystemAreaFunctionality belongs to exactly one SystemArea, a straightforward one-to-many relationship using a foreign key.

Note: it might be that you have a many-to-many relation, the answer will be similar

Alas you forgot to write your classes, so I'll give a shot:

class SystemArea
{
    public int Id {get; set;}
    ... // other properties

    // every SystemArea has zero or more SystemAreaFunctionalities (one-to-many)
    public virtual ICollection<SystemAreaFunctionality> SystemAreaFunctionalities {get; set;}
}

class SystemAreaFunctionality
{
    public int Id {get; set;}
    ... // other properties

    // every SystemAreaFunctionality belongs to exactly one SystemArea, using foreign key
    public int SystemAreaId {get; set;}
    public virtual SystemArea SystemArea {get; set;}
}

In entity framework the columns of your tables are represented by non-virtual properties, the virtual properties represent the relationships between the tables. (one-to-many, many-to-many, ...)

for completeness:

class CurrentContext : DbContext
{
    public DbSet<SystemArea> SystemAreas {get; set;}
    public DbSet<SystemAreaFunctionality> SystemAreaFunctionalities {get; set;}
}

If people want items with their sub-items, like Schools with their Students, Customers with their Orders, etc. people tend to perform a (group)Join. However, when using entity framework joins are seldom necessary. Ise the ICollections instead. Entity framework knows the relationships and knows which (group)join to perform.

Regularly I see people use Include, but if you do that, you'll select the complete object, which is not very efficient. Suppose you have a SystemArea with Id = 10, and 1000 SystemAreaFunctionalities, you know that every SystemAreaFunctionality has a foreign key SystemAreaId with a value 10. Instead of sending this value only once as primary key of SystemArea, Include will also select all 1000 foreign keys with this value 10. What a waste of processing power!

When querying data, always use Select and select only the properties you actually plan to use. Only use Include if you plan to Update the included object.

You wrote:

SystemAreaFunctionality is the child object that i am trying to convert here...

It is not clear what you really want. Do you want a collection of all used SystemAreaCodes? Or do you really want a collection of new SystemAreaFunctionalities where only one field is filled: SystemAreaCode? Because of you use of singular property name, it seems you don't want a collection but only one item.

var result = currentContext.SystemAreas.Select(systemArea => new
{
     Id = systemArea.Id,
     Code = systemArea.Code,
     ...

     // if you want a collection of SystemAreaFunctionalities
     // where every SystemAreaFunctionality is filled with only SysemAreaCode
     // do the following:
     SystemAreaFunctionalities = systemArea.SystemAreaFunctionalities
          .Select(systemAreaFunctionality => new SystemAreFunctionality
          {
               SystemAreaCode = systemAreaFunctionality.SystemAreaCode,
          })
          .ToList(),   // DON'T FORGET THIS, OR YOU WON'T GET RESULTS!
    })
    .ToList()
}

I think the cause of your empty SystemAreaFunctionalities is because you forgot to do ToList().

Because you used ToList(), you automatically have the Count of the selected SystemAreaFunctionalities. There is no need to select this Count separately.

One of the slower parts of database queries is the transport of the selected data from the database management system to your local process. It is good practice to only select data you actually plan to use

You query is not very efficient because you select complete SystemAreaFunctionalities and fill only the SystemAreaCode. All other fields will be filled by default values. Apart from the slower query, you also give your callers the impression that they get properly filled SystemAreaFunctionalities. An improved version would be:

var result = currentContext.SystemAreas.Select(systemArea => new
{
     // select only the properties you actually plan to use
     Id = systemArea.Id,
     Code = systemArea.Code,
     ...


     // if you only need the SystemAreaCodes, select only that property
     SystemAreaCodes = systemArea.SystemAreaFunctionalities
          .Select(systemAreaFunctionality => systemAreaFunctionality.SystemAreaCode)
          .ToList(),
    })
    .ToList()
};

Of courds, if you need mrre than only the SystemAreaCodes, but several SystemAreaFunctionalities, go ahead, select them:

...
SystemAreaFunctionalities = systemArea.SystemAreaFunctionalities
    .Select(systemAreaFunctionality => new
    {
        // again: select only the properties you plan to use!
        Id = systemAreaFunctionality.Id
        SystemAreaCode = systemAreaFunctionality.SystemAreaCode,
     })

Entity To DTO Conversion for a Spring REST API, In this tutorial, we'll handle the conversions that need to happen between the internal entities of a Spring application and the external DTOs  In general, DTOs should contain only data and not business logic; it is up to the supplying and receiving systems to determine what to do with the data a DTO carries. In our case, the DTOs ended up being our DataContract classes. So, our Entity Framework object might look like this:

An include should do the trick for you like so:

    IEnumerable<SystemArea> result = (from sa in CurrentContext.systemarea.Include("systemareafunctionality")                                 
                             select new SystemArea
                             {
                                 SystemAreaId = sa.SystemAreaId,
                                 SystemAreaCode = sa.SystemAreaCode,
                                 SystemAreaType = sa.SystemAreaType,
                                 SystemAreaDescription = sa.SystemAreaDescription,
                                 SystemAreaCreatedDate = sa.SystemAreaCreatedDate,
                                 SystemAreaUpdateDate = sa.SystemAreaUpdateDate,
                                 SystemAreaStatus = sa.SystemAreaStatus,
                                 Count = sa.systemareafunctionality.Count,
                                 SystemAreaFunctionality = sa.systemareafunctionality.Select(e => new SystemAreaFunctionality { SystemAreaCode =e.SystemAreaCode })
                             }).ToList();

DTO to Entity and Entity to DTO Conversion, Related Posts: Java Objects Mapping with ModelMapper · Select Specific Columns with JPA Native Query · Spring MVC and JPA - Save to a  In summary, what it does is to populate an instance of a DTO, defined in the @DTO annotation, and then maps the properties of this DTO into an entity. What makes it a little bit more magic is that instead of always populating a new instance of an entity, it first checks if there is an @Id property in the DTO to see if it needs to fetch a pre

Java Objects Mapping with ModelMapper, And also when converting a DTO to a REST Model Object which will then be returned back as an entity object in the body of HTTP Response. For  Why mapping DTOs to Entities using AutoMapper and EntityFramework is horrible December 1, 2013 Roger Johansson .NET , C# , DDD , Entity Framework 47 comments One of the most common architectures for web apps right now is based on passing DataTransferObjects(DTOs) to and from CRUD services that updates your business/domain entities using tools

Question: Is Type Mapping order important for Parent-Child entities , have Parent and Child entity (with DTOs): public class Parent { private Stri GitHub is home to over 50 million developers working together to host to have each converter class for each entities and have these mapping  Adding a related entity. If you reference a new entity from the navigation property of an entity that is already tracked by the context, the entity will be discovered and inserted into the database. In the following example, the post entity is inserted because it is added to the Posts property of the blog entity which was fetched from the database.

Automatically Mapping DTO to Entity on Spring Boot APIs, DTO, which stands for Data Transfer Object, is a design pattern want these DTOs to be converted to our entities as automatically as possible, we I find amazing to think about how all pieces work together to provide a fast  Create Data Transfer Objects (DTOs) 06/16/2014; 2 minutes to read +2; In this article. by Mike Wasson. Download Completed Project. Right now, our web API exposes the database entities to the client. The client receives data that maps directly to your database tables. However, that's not always a good idea.

Comments
  • Is sa.systemareafunctionality an IQueryable?
  • no its ICollection
  • If it wasn't there you would bet an error. Add ToList() : SystemAreaFunctionality = sa.systemareafunctionality.Select(e => new SystemAreaFunctionality { SystemAreaCode =e.SystemAreaCode }).ToList()
  • What EF is this (6 or Core)?
  • @IvanStoev sorry for delayed answering, have posted what i experienced and answered accordingly. Please also feel free to correct me.
  • I don't think join made any difference here, because i tried join before making it a normal select query.
  • did you try left join like this: join systemareafunctionality in CurrentContext.systemareafunctionality on sa.systemareafunctionalityID equals systemareafunctionality.ID into item1 from subitem1 in item1.DefaultIfEmpty()
  • yes i did, anyways it is a child table so ef context will have the data inside its parent
  • did you try to make LazyLoadingEnabled set true?
  • Tried what you mentioned did not yield anything, SystemArea has one to many relationship only with SystemAreaFunctionality also my query is perfect because i need all the information available, i just did not add it in the code posted in question.