将枚举映射到具有相同枚举类型的属性的类
假设我有一个具有以下定义的类:
public class DestinationOuter
{
public string Name { get; set; }
public int Age { get; set; }
public List<DestinationInner> Siblings { get; set; }
}
public class DestinationInner
{
public string Name { get; set; }
public RelationEnum Relation { get; set; }
}
并假设我有一个源类型:
public class SourceSiblings
{
public string Name { get; set; }
public RelationEnum Relation { get; set; }
}
使用 AutoMapper,我可以轻松创建一个从 SourceSiblings
映射到 DestinationInner
的配置,这让我像这样进行映射:
SourceSiblings[] brothers = { ... };
DestinationOuter dest = new DestinationOuter();
Mapper.Map(brothers, dest.Siblings);
但我希望能够做的是直接从 SourceSiblings
映射到 DestinationOuter
。在这种情况下,DestinationOuter
中的 Name 和 Age 属性将在映射中被忽略,但其想法是 SourceSiblings
将映射到 DestinationOuter.Siblings.使用上面的对象声明,我希望能够做到:
Mapper.Map(brothers, dest);
我不知道如何让它工作。我可以像这样设置配置:
CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>();
但这没有任何作用。看来我需要能够这样说:
CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>()
.ForMember(dest => dest.Siblings,
opt => opt.MapFrom(src => src));
虽然上面的代码编译了,但 Mapper.Map 实际上并不映射值。
Say I have a class with the following definition:
public class DestinationOuter
{
public string Name { get; set; }
public int Age { get; set; }
public List<DestinationInner> Siblings { get; set; }
}
public class DestinationInner
{
public string Name { get; set; }
public RelationEnum Relation { get; set; }
}
And say I have a source type:
public class SourceSiblings
{
public string Name { get; set; }
public RelationEnum Relation { get; set; }
}
With AutoMapper I can easily create a configuration that maps from SourceSiblings
to DestinationInner
, which let's me do a mapping like so:
SourceSiblings[] brothers = { ... };
DestinationOuter dest = new DestinationOuter();
Mapper.Map(brothers, dest.Siblings);
But what I'd like to be able to do is map directly from SourceSiblings
to DestinationOuter
. In this case, the Name and Age properties in DestinationOuter
would be ignored in the mapping, but the idea is that SourceSiblings
would be mapped onto DestinationOuter.Siblings
. Using the object declarations above, I'd like to be able to do:
Mapper.Map(brothers, dest);
I'm not sure how to get this to work. I can setup the configuration like so:
CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>();
But that doesn't do anything. It seems like I need to be able to say something like:
CreateMap<IEnumerable<SourceSiblings>, DestinationOuter>()
.ForMember(dest => dest.Siblings,
opt => opt.MapFrom(src => src));
And while the above compiles, Mapper.Map
does not actually map the values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段代码似乎对我有用,但你所说的几乎没有任何作用。
This code seems to work for me, but it's pretty much what you said doesn't do anything.