且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使Dapper返回空字符串而不是空字符串

更新时间:2023-02-17 08:38:26

Dapper看到 null 时不会调用任何setter,因此选项可能包括:

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


  • 在构造函数中将默认值设置为

  • 在访问器中检查 null

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

所以:

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;} }
}

但是,仅此适用于读取值;我想不出一种 nice 的方法,可以使精巧的人将 转换为 null 将dto作为参数对象传递时;选项包括:

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:


  • 创建匿名类型,将 替换为 null (也许写一个字符串NullIfBlank(此字符串s)扩展方法)

  • 在返回 null 的类型上具有shim属性,而不是 ,并且将数据库查询绑定到 @NameOrNull 而不是 @Name

  • 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