c# - Dapper.Contrib- "only supports an entity with a single [Key] or [ExplicitKey]"

标签 c# dapper dapper-contrib

我正在使用 DapperDapper.Contrib在 MVC5 c# 环境中,有时(!)当我部署生产站点时,我收到错误消息:

GetAll<T> only supports an entity with a single [Key] or [ExplicitKey] property at Dapper.Contrib.Extensions.SqlMapperExtensions.GetSingleKey[T](String method) at Dapper.Contrib.Extensions.SqlMapperExtensions.GetAllAsync[T](IDbConnection connection, IDbTransaction transaction, Nullable`1 commandTimeout)

虽然这种情况只发生在大约三分之一的部署中。

我怀疑以某种方式 Dapper.Contrib自动注意到我的主键,因为它被命名为 “Id”,但我用 [ExplicitKey] 装饰了它(它是一个 GUID),也许这些属性会发生冲突。也许这是完全不同的东西......

除了可能重命名我的主键之外,关于如何解决这个问题有什么想法吗?

来自相关模型的片段:

[Table("Tasks")]
public class TasksModel
{
    [ExplicitKey]
    public Guid Id { get; set; }

...

最佳答案

我认为这与属性名称“id”有关。以下来自Dapper/SqlMapperExtensions.cs中的KeyCache构建代码,当没有具有 [Key] 属性的属性时。

var idProp = allProperties.Find(p => string.Equals(p.Name, "id", StringComparison.CurrentCultureIgnoreCase));

在您的例子中,您同时获得了一个 ExplicitKey(通过在您的模型中使用 [ExplicitKey] 装饰您的键)和一个 Key(默认情况下,因为此属性称为 Id)。除非您可以更改数据库列名称,否则我会使用常规 Dapper。

关于c# - Dapper.Contrib- "only supports an entity with a single [Key] or [ExplicitKey]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45880051/

相关文章:

c# - 使用 iTextSharp 4.1.6.0 对 PDF 进行数字签名

c# - 如何用dapper解析Sql Script? (设置 PARSEONLY ON + Dapper)

c# - 如何防止返回的 Json 被拆分?

c# - 根据场景插入应映射到不同数据库表的对象

c# - 使用存储过程连接数据库中的 4 个表?

c# - 如何在不使用^的情况下实现XOR?

c# - ChannelFactory 引发的 WCF 异常

c# - 如何使用 Dapper.NET 将 sql 结果存储到 C# 中的变量

c# - dapper.contrib postres 42P01 错误 : relation "<table name>" does not exist

c# - Dapper贡献:为什么找不到 key ?