使Dapper返回空字符串而不是空字符串 [英] Getting Dapper to return an empty string instead of a null string

查看:169
本文介绍了使Dapper返回空字符串而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这样做是错误的事情,但是我正在处理的是一个包含NULL的旧代码库,这意味着空字符串,反之亦然。

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.

我无法立即看到它是如何实现的,但是在以下情况下是否有可能获得(或修改dapper)返回空字符串而不是空字符串?从数据库映射回来。

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.

推荐答案

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

这篇关于使Dapper返回空字符串而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆