Mackan
Mackan

Reputation: 6271

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

I'm using Dapper and Dapper.Contrib in an MVC5 c# environment and sometimes (!) when I deploy the production site I get errors stating:

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)

This only happens about one every third deploy though.

I'm suspecting that somehow Dapper.Contrib notices my primary key automatically, as it's named "Id", but I've decorated it with [ExplicitKey] (it's a GUID) and perhaps those attributes clash. Perhaps it's something entirely different...

Any idea on how to get around this problem, other than possibly renaming my primary key?

A piece from the model in question:

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

...

Upvotes: 11

Views: 7801

Answers (1)

Srdja V
Srdja V

Reputation: 11

I think this is related to the name of the property, "id". The following is from the KeyCache building code in Dapper/SqlMapperExtensions.cs, when there are no properties with the [Key] attribute.

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

In your case, you get both an ExplicitKey (by decorating your key with [ExplicitKey] in your model), and a Key (by default as this property is called Id). Unless you can change the DB column name, I would use regular Dapper.

Upvotes: 1

Related Questions