我在这里检查了SO&谷歌一般都有类似的问题,但未能找到答案。这段代码应该显示我当前的场景:
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);
因此,这是关于使用用户进行更改来更新已保留在数据库上的现有项目。 EntityDto
实例取自实体框架,其中DbContext将开始跟踪EntityDto
和NestedEntityDto
。 Entity
实例改为包含用户所做的更改,例如通过MVC / API PUT操作。
mapper.Map<Entity, EntityDto>(entity, entityDto);
代表了将Entity
深深克隆到现有EntityDto
实例中的快速(针对开发人员)方式。
问题是第一级实体的实例实际上是重用的(entityDto
),但嵌套实体实例不会发生同样的情况。从我当前的测试中,创建了NestedEntityDto
的新实例并将其分配给EntityDto
。这搞砸了EF Change Tracking,因为现在有两个嵌套的实体实例具有相同的ID等等。
那么:我如何让AutoMapper不仅为第一级目标对象重用同一个实例,还为其嵌套属性重用?有没有办法实现这个目标?谢谢大家
环境:ASP.NET Core 1.0,EF Core 1.0,AutoMapper 5.0.2,C#6
答案 0 :(得分:0)
我的解决方案暂时基本上是使用AutoMapper来映射顶级类(Entity
&amp; EntityDto
),同时继续使用它来映射嵌套类。
在我的场景中,顶级类有一些属性,而有更多嵌套类具有自己的属性,所以我的 be-lazy 平衡让我有一个自定义映射器用于手动映射顶级类并手动保留实例。这需要IMapper
依赖关系以映射嵌套类,并在需要时重用现有实例。
当然这种方法很有效,因为我只对顶级和第一级嵌套级别的实例保留感兴趣。同样,如果我必须在下面的级别上保留实例,它将无法工作。
编辑:几个月后......
我在同一个问题上再次招致,这次至少可以在SO上找到一些可行的解决方法。对于未来的读者: