Dapper.SimpleCRUD Insert / Update / Get fails with message "Entity must have at least one [Key] property"

user2066540 picture user2066540 · Oct 21, 2015 · Viewed 9.2k times · Source

I'm a new baby in Dapper. Trying to incorporate CRUD operations with Dapper and Dapper.SimpleCRUD lib. Here is the sample code...
My Data Model Looks like

Class Product
{
  public string prodId {get;set;}
  public string prodName {get;set;}
  public string Location {get;set;}
}

Dapper Implementation - Insert

public void Insert(Product item)
{
    using(var con = GetConnection())
    {
      con.Insert(item);
    }
}

Since the ProdId in the Db is an Identity Column it fails. How does it indicate ProdId is an Identity Column in DB?

Dapper Implementation - Get

public IEnumerable<Product> GetAll()
{
        IEnumerable<Product> item = null;
        using (var con = GetConnection())
        {
            item = con.GetList<Product>();
        }
        return item;
}

It gives an exception:

"Entity must have at least one [Key] property"!

Answer

Mrinal Kamboj picture Mrinal Kamboj · Oct 21, 2015

This is happening since you are using a Dapper Extension, which has implemented the Insert CRUD extension method. Ideally this can be achieved using simple

con.Execute in the Dapper, but since you want to pass an object and create an insert query automatically by the extension, you need to help it understand, which is the Primary Key for the given product entity, following modification shall help:

[Key]
public string prodId {get;set;}

where Key attribute shall be either implemented in Dapper Extension or the Component Model.

Alternatively you may rename prodId to Id, which will automatically make it the key. Also check the following link, where you can create a separate mapper for the entity, thus defining the key, whatever works in your case