ExpressMapper - 空到 string.Empty

ExpressMapper - null to string.Empty

我正在使用 ExpressMapper 将 Linq-To-Sql 对象映射到另一个对象 - 但我的字符串中的空值导致了问题。 有没有办法从 ExpressMapper 中将这些空值转换为 string.Empty

例如鉴于以下 类:

class A
{
    string a = null;
}

class B
{
    string a;
}

进行转换时

B b = Mapper.Map<A, B>(new A(), new B());

我想要 b.a == "" 而不是 b.a == null

您可以使用Member函数:

Mapper.Register<A,B>().Member(dest => dest.a, src => src.a == null ? string.Empty : src.a);

可以使用null-coalescing operator

string a = "";
string b = null;

string c = a ?? "xyz"; //a is not null, so empty string is assigned to c
string d = b ?? "xyz"; //b is null, so "xyz" is assigned to d

通过这种方式,您可以简化对此的调用:

B b = Mapper.Map<A, B>(new A(), new B());
b.a = b.a ?? "";
//"" can be String.Empty, whichever you prefer for your code style.