Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for all string properties when source properties are null

Tags:

c#

automapper

Is it possible to set all string properties that are null in my source object to some default value within my destination object using AutoMapper?

For example, let's say I had the following two class definitions:

public class UniversalForm
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string FaxNumber { get; set; }
    ...
}

public class UniversalFormDto
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string FaxNumber { get; set; }
    ...
}

Now, MiddleName and FaxNumber are properties that are likely to be null in the UniversalForm class. So what I would like to be able to do is if FaxNumber or MiddleName are null then in UniversalFormDto object I would like for the value of the corresponding properties to be set to "N/A".

I know this can be accomplished by creating a mapping for each individual member, but I would like to avoid that if at all possible.

I'm looking for a way to define a default value for all my string properties to be used when the corresponding property on my source object (UniversalForm) is null.

like image 309
Rudy Padron Avatar asked Aug 05 '15 22:08

Rudy Padron


People also ask

Is string default value null?

Because string is a reference type and the default value for all reference types is null .

What is default value of char in C#?

The default value of the char type is \0 , that is, U+0000.

IS null a string type?

It is a character sequence of zero characters. A null string is represented by null . It can be described as the absence of a string instance.


1 Answers

Here's a few methods I know:

ForAllMembers

All null values on all properties will be substituted as "N/A". Will crash if any of the properties can't be mapped to a string:

cfg.CreateMap<UniversalForm, UniversalFormDto>()
.ForAllMembers(opt => opt.NullSubstitute("N/A"));

ForMember

A substitute for every individual property:

cfg.CreateMap<UniversalForm, UniversalFormDto>()
.ForMember(dto => dto.FirstName, opt => opt.NullSubstitute("N/A"))
...
;

ConvertUsing

Universal substitute for all null strings in any property:

cfg.CreateMap<string, string>().ConvertUsing(s => s ?? "N/A");
like image 121
Aske B. Avatar answered Sep 30 '22 15:09

Aske B.