英文:
Map Different Concrete Types to Collection of Interface
问题
我在使用AutoMapper将不同的具体类型映射到一个接口集合时遇到困难。例如:
领域模型:
public interface INameInterface {
string Name;
}
public class FullName : INameInterface {
string Name;
}
public class FirstNameOnly : INameInterface {
string Name;
}
public class MyDomain {
List<INameInterface> Names;
}
DTO模型:
public class NameDTO {
int NameType;
string Name;
}
public class MyDTO {
List<NameDTO> NameDTOs;
}
我想将MyDTO映射到MyDomain。我想根据NameDTO的NameType解析它,并将NameType 1映射到FullName,将NameType 2映射到FirstNameOnly的具体类,并将它们放在MyDomain.Names集合中。如何在AutoMapper中实现这个目标?
非常感谢任何帮助。
注:示例已经简化。
英文:
I'm having difficulty in mapping different concrete types to a single collection of interface in automapper. For example:
Domain:
public interface INameInterface {
string Name;
}
public class FullName: INameInterface {
string Name;
}
public class FirstNameOnly: INameInterface {
string Name;
}
public class MyDomain {
List<INameInterface> Names;
}
DTOs:
public class NameDTO {
int NameType;
string Name;
}
public class MyDTO {
List<NameDTO> NameDTOs;
}
I would like to map MyDTO to MyDomain. I would like to resolve NameDTO by its NameType and map NameTypes 1 to Fullname and 2 to FirstNameOnly concrete classes and place them in MyDomain.Names collection. How can I do it in automapper.
Any help is highly appreciated.
PS. Example is simplified
答案1
得分: 1
可以使用自定义类型转换器来解决这个问题。
在automapper配置中:
cfg.CreateMap<NameDTO, INameInterface>()
.ConvertUsing<SomeConverter>();
然后创建自定义转换器类。
public class SomeConverter : ITypeConverter<NameDTO, INameInterface>
{
public INameInterface Convert(NameDTO source, INameInterface destination, ResolutionContext context)
{
if (source.NameType == 0)
{
return context.Mapper.Map<FullName>(source);
}
if (source.NameType == 1)
{
return context.Mapper.Map<FirstNameOnly>(source);
}
return context.Mapper.Map<FirstNameOnly>(source);
}
}
只需为每个具体类型添加必要的映射。
不过需要注意的是,我尝试在投影中使用这种方法,但这不会起作用,因为它无法转换为表达式。
英文:
This can be solved using custom type converter.
In automapper config:
cfg.CreateMap<NameDTO, INameInterface>()
.ConvertUsing<SomeConverter>();
Then create the custom converter class.
public class SomeConverter : ITypeConverter<NameDTO, INameInterface>
{
public INameInterface Convert(NameDTO source, INameInterface destination, ResolutionContext context)
{
if (source.NameType == 0)
{
return context.Mapper.Map<FullName>(source);
}
if (source.NameType == 1)
{
return context.Mapper.Map<FirstNameOnly>(source);
}
return context.Mapper.Map<FirstNameOnly>(source);
}
}
Just add the necessary mapping for each concrete types.
Warning tho, I have tried to use this approach in projection but this won't work as it cannot be converted to an expression.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论