Getting Dapper to return an empty string instead of a null string

dapper

Question

I know it's kind of the wrong thing to do, but I'm dealing with a legacy codebase that has NULLS when it means empty strings and vice versa.

I can't immediately see how it is possible, but is it possible to get (or modifiy dapper so it will) return an empty string instead of a null string when mapping back from the database.

Accepted Answer

Dapper doesn't call any setter when it sees a null, so options might include:

  • set the default value to "" in the constructor
  • check for null in the accessor

So:

public class SomeDto
{
    public SomeDto()
    {
        Name = "";
    }
    public string Name {get;set;}
}

or:

public class SomeDto
{
    private string name;
    public string Name { get {return name ?? "";} set {name = value;} }
}

However, this only applies to reading values; I can't think of a nice way to get dapper to turn "" into null when passing the dto in as the parameter object; options include:

  • creating an anon-type, substituting "" to null (perhaps write a string NullIfBlank(this string s) extension method)
  • having a shim property on the type that returns null in place of "", and have your database query bind to @NameOrNull rather than @Name

Popular Answer

You can control this with your queries, for example:

    public class Data
    {
        public string Foo { get; set; }
    }

    var result = conn.Query<Data>("select Foo = coalesce(Foo, '') from MyTable");

So in the above example, coalesce will return an empty string when Foo is null.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why