C# 使用automapper从实体构建xml
我想使用AutoMapper从实体创建一个xml片段。 大致如下:C# 使用automapper从实体构建xml,c#,xml,automapper,C#,Xml,Automapper,我想使用AutoMapper从实体创建一个xml片段。 大致如下: public class SourceEntity { public int MasterId { get; set; } } public class MappingProfile : Profile { public MappingProfile() { CreateMap<SourceEntity, XElement>() .ForMember(
public class SourceEntity
{
public int MasterId { get; set; }
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<SourceEntity, XElement>()
.ForMember(
dest => dest.Element("Asset.ID"),
options => options.MapFrom(x => x.MasterId));
}
}
我得到这个错误:
OneTimeSetUp:AutoMapper.AutoMapperConfigurationException:成员的自定义配置仅支持类型上的顶级单个成员
我最终尝试创建这样一个XElement:
var config = new MapperConfiguration(
cfg => { cfg.AddProfile(new MappingProfile()); });
var mapper = config.CreateMapper();
XElement retVal = new XElement("Asset",
new XElement("ID", src.MasterId)
);
使用.ToString()返回以下内容:
<Asset><ID>789</ID></Asset>
789
元素“Asset.ID”不是顶级成员。试着用“资产”来代替。谢谢@jdweng,我已经试过了——应该已经澄清了。我也需要它去更深一层。我将添加一些预期的输出。我认为您需要使用Initialize。请参阅:不确定是这样,我已经在使用MappingProfile:Profile,然后使用var config=new-MapperConfiguration(cfg=>{cfg.AddProfile(new-MappingProfile());}实例化映射器_mapper=config.CreateMapper();出现此错误是因为您正在为目标成员指定方法,而AutoMapper不允许这样做。在这种情况下,错误消息有点误导。ForMember()
只支持嵌套的属性和字段。此外,AutoMapper对于从对象创建XML来说是一个错误的工具。您应该查找转换代码,从对象生成XElement
s,如。