C# 汽车制造商。如果源成员为空,则映射
我有两个类,用Automapper将一个类映射到另一个类。例如:C# 汽车制造商。如果源成员为空,则映射,c#,.net,automapper,C#,.net,Automapper,我有两个类,用Automapper将一个类映射到另一个类。例如: public class Source { // IdName is a simple class containing two fields: Id (int) and Name (string) public IdName Type { get; set; } public int TypeId {get; set; } // another members } public clas
public class Source
{
// IdName is a simple class containing two fields: Id (int) and Name (string)
public IdName Type { get; set; }
public int TypeId {get; set; }
// another members
}
public class Destination
{
// IdNameDest is a simple class such as IdName
public IdNameDest Type { get; set; }
// another members
}
然后我使用Automapper将源
映射到目标
:
cfg.CreateMap<Source, Destination>();
有可能使用AutoMapper吗 在声明映射时,可以使用
.ForMember()
方法。
像这样:
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id }));
cfg.CreateMap()
.FormMember(dest=>dest.Type,opt=>opt.MapFrom(src=>src.Type!=null?src.Type:new-IdNameDest{Id=src.Id}));
虽然LeeeonTMs answer工作正常,但AutoMapper提供了一种专门的机制来替换空值。它“允许您在源值沿成员链的任何位置为空时为目标成员提供备用值”(取自)
例如:
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.NullSubstitute(new IdNameDest { Id = src.Id }));
cfg.CreateMap()
.ForMember(dest=>dest.Value,opt=>opt.NullSubstitute(新的IdNameDest{Id=src.Id}));
有帮助吗?Gr8回答m9。
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Value, opt => opt.NullSubstitute(new IdNameDest { Id = src.Id }));