【问题标题】:How to get Dapper to ignore/remove underscores in field names when mapping?映射时如何让 Dapper 忽略/删除字段名称中的下划线?
【发布时间】:2015-12-30 16:33:14
【问题描述】:

有很多方法可以将数据库字段名映射到类名,但是删除下划线最简单的方法是什么?

    public IEnumerable<PersonResult> GetPerson(int personId)
    {
        using (var dbConnection = _dbConnectionFactory.Create(ConnectionStrings.ProjectXYZ))
        {
            IEnumerable<PersonResult> result =
                dbConnection.Query<PersonResult>("fn_get_person", new { personId },
                    commandType: CommandType.StoredProcedure).ToList();

            return result;
        }
    }

表和数据库字段:

person
-------- 
person_id
full_name

有效的类:(dapper 已经忽略了大写)

public class PersonResult
{    
    public int Person_Id { get; set; }
    public string Full_Name { get; set; }
}

我想把课程改成什么:

public class PersonResult
{    
    public int PersonId { get; set; }
    public string FullName { get; set; }
}

【问题讨论】:

  • 您确定您使用的是 PostgreSQL 而不是 SQL Server?
  • 是的。 :) 猜你问是因为命令类型是“存储过程”而 postgresql 只有函数?它仍然有效。

标签: postgresql mapping dapper


【解决方案1】:
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;

工作完成;p

【讨论】:

  • 哇。我把它放在我的连接工厂中,它可以工作,但是还有更好的地方吗?
  • @scw 好吧,您可以编写自己的类型映射实现...但是:这行得通
  • 有没有办法为单个 Dapper 调用有条件地做到这一点?
  • 此外,这似乎不适用于构造函数参数。是故意的吗?对我来说似乎不直观/不一致,当设置此标志时它会尝试匹配没有下划线的成员,但不会对 ctor 参数执行相同的操作。标志名称通常涉及names,因此可以预期所有名称匹配逻辑都会受到影响。
  • @juleagon 不,不是故意的;我建议在 github 上记录一个错误;编辑:我看到你已经有了 - 谢谢
【解决方案2】:

readme 不支持重命名列。你可以给他们起别名select:

select person_id as personid, full_name as fullname from fn_get_person();

this answer 建议的那样。

【讨论】:

  • 其实是支持的-看我的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2020-10-26
  • 2021-12-29
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多