I've checked here on SO & Google in general for similar questions, but was not able to find an answer. This block of code should show my current scenario:
class Entity
{
Guid EntityId { get; set; }
string EntityName { get; set; }
NestedEntity Nested { get; set; }
// more domain methods
}
class NestedEntity
{
Guid NestedId { get; set; }
string NestedName { get; set; }
string NestedDescription { get; set; }
// more domain methods
}
class EntityDto
{
Guid EntityId { get; set; }
string EntityName { get; set; }
NestedEntityDto Nested { get; set; }
}
class NestedEntityDto
{
Guid NestedId { get; set; }
string NestedName { get; set; }
string NestedDescription { get; set; }
}
class MyMappingProfile : Profile
{
CreateMap<Entity, EntityDto>();
CreateMap<NestedEntity, NestedEntityDto>();
}
// that profile gets added to configuration, not shown here
// IMapper is registered and injected as a dependency, not shown here
EntityDto entityDto = GrabFromEntityFrameworkDbContext();
Entity entity = GrabChangesByUser();
mapper.Map<Entity, EntityDto>(entity, entityDto);
So, this is about updating an existing item, already persisted on DB, with changes made by user. An EntityDto
instance is taken from Entity Framework, where DbContext will start tracking both EntityDto
and NestedEntityDto
. An Entity
instance instead contains changes made by user, e.g. through a MVC/API PUT action.
mapper.Map<Entity, EntityDto>(entity, entityDto);
represents a quick (for developer) way to deeply clone Entity
into an existing instance of EntityDto
.
Problem is that the instance of first-level entity is actually re-used (entityDto
), but the same does not happen for nested entity instance. From my current tests, a new instance of NestedEntityDto
is created and assigned to EntityDto
. That screws up EF Change Tracking, because now there are two nested entity instances around with the same ID, etc.
So: how do I make AutoMapper reuse the same instance not only for first level destination object, but also for its nested properties? Is there a way to achieve this? Thanks all
Environment: ASP.NET Core 1.0, EF Core 1.0, AutoMapper 5.0.2, C#6