

AutoMapper will now know when to create a DetailSet.First(d => d.Id = detailDTO.Id) let automapper be able to find or create the entity based on Id
#Ef select to new dto with icollections update
So even if we can create and update the order entity, we are still messed up when dealing with the details. We still create new entities every time for each detail, AutoMapper knows nothing about EF and ID’s so it will simply recreate every object in the. Now we will not add new orders every time we try to update an existing one. Map the DTO to our _existing_ or new order if no order was found, create a new and add it to the context try to fetch an existing order with the same Id as the DTO We will get into trouble because of the, existing orders will become new orders in the DB because we are always “adding”. This will work fine for a new order, the above code will map from DTOs to new entities and then add the new entities to the dbcontext and save the changes.īut what happens if we pass an existing order? this code would probably reside somewhere else, So what do we need to do in order to make this work? Public void CreateOrUpdateOrder(OrderDTO orderDTO) Lets also assume there is some sort of service that updates orders: I’m pretty sure you have seen something similar to this before. The scenario here is an Order service with an Order entity and an OrderDTO. Horrible from a technical perspectiveįirstly, lets set up a scenario that we can reason about here:

I will try to explain why this is a truly horrible approach. 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 like AutoMapper and EntityFramework.
