automapper c# set default values if field is null
- User
automapper c# set default values if field is null
- Assistant
In AutoMapper, you can set default values for fields if they are
nullby using a custom mapping configuration. Here are a few ways to achieve this in C#:Method 1: Use
ForMemberto specify default valuesYou can configure the mapping for specific properties using the
ForMembermethod. This allows you to check if the source property isnulland assign a default value if it is.csharpusing AutoMapper; public class Source { public string Name { get; set; } public string Description { get; set; } } public class Destination { public string Name { get; set; } public string Description { get; set; } public string DefaultDescription { get; set; } } public class MappingProfile : Profile { public MappingProfile() { CreateMap<Source, Destination>() .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description ?? "Default Description")); } } // Usage var config = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile())); var mapper = config.CreateMapper(); var source = new Source { Name = "Source Name", Description = null }; var destination = mapper.Map<Destination>(source); // destination.Description will be "Default Description"Method 2: Use a Value Resolver
If you have more complex logic for determining the default value, you might want to use a custom value resolver:
csharppublic class DefaultDescriptionResolver : IValueResolver<Source, Destination, string> { public string Resolve(Source source, Destination destination, string destMember, ResolutionContext context) { return source.Description ?? "Default Description"; } } // Update the MappingProfile to use the resolver public class MappingProfile : Profile { public MappingProfile() { CreateMap<Source, Destination>() .ForMember(dest => dest.Description, opt => opt.MapFrom<DefaultDescriptionResolver>()); } }