【问题标题】:Dapper sqlmapperextensions automatically adds "s" to tablename?Dapper sqlmapperextensions 自动将“s”添加到表名?
【发布时间】:2014-12-07 08:45:40
【问题描述】:

这是我第一次使用 Dapper.Contrib(来自 Nuget 的最新版本),这是一个奇怪的情况:

using (SqlConnection cn = new SqlConnection(connectionString))
{
    cn.Open();
    var product = cn.Get<Product>(1);
}

在 SqlMapperExtensions 上,它会引发错误 Invalid object name 'Products':

public static T Get<T>(this IDbConnection connection,
                       dynamic id, 
                       IDbTransaction transaction = null, 
                       int? commandTimeout = null) where T : class
{
    var type = typeof(T);
    string sql;
    if (!GetQueries.TryGetValue(type.TypeHandle, out sql))
}

数据库接收到的命令select * from Products where Id = @id是错误的。

为什么要在 Product 后面加上 s

我尝试过使用其他表并得到相同的结果。

【问题讨论】:

    标签: c# dapper


    【解决方案1】:

    就是这样设计的。您可以通过使用Dapper.Contrib.Extensions.TableAttribute 装饰您的POCO 类 来覆盖默认行为。

    using Dapper.Contrib.Extensions;
    
    [Table("Product")]
    public class Product
    {
    ...
    }
    

    【讨论】:

    • 您的回答很好,尽管让 Dapper 依赖于 POCO 程序集不是一个好习惯,如果您使用 System.ComponentModel.DataAnnotations.Schema,Dapper 会很高兴;而不是使用 Dapper.Contrib.Extensions
    【解决方案2】:

    好像是这样写的,可以查看source code

    或者更具体地说:

    private static string GetTableName(Type type)
    {
        //.... codes
    
        if (TableNameMapper != null)
        {
            name = TableNameMapper(type);
        }
        else
        {
            var tableAttr = //.... lookup attribute
            if (tableAttr != null)
                name = tableAttr.Name;
            else
            {
                name = type.Name + "s";
                if (type.IsInterface() && name.StartsWith("I"))
                        name = name.Substring(1);
            }
        }
    

    如果您想使用文字类型名称,您可以轻松配置它。

    SqlMapperExtensions.TableNameMapper = (type) => {
        //use exact name
        return type.Name;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 2017-01-27
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2020-12-24
      相关资源
      最近更新 更多