这是我对 Dapper的初次体验。贡献(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

为什么将s附加到产品?

我试过其他表,并得到相同的结果。

最佳答案

看来是这样写的,您可以检查 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;
};

10-06 13:28
查看更多