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

假装没事ソ 提交于 2019-12-10 13:33:40

问题


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"!


回答1:


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




回答2:


Connecting to SQL Server 2016, I had this error with both Dapper.Contrib & Dapper.SimpleCRUD when I forgot to attach the Primary Key to the Id column of the table.

Primary Key added to the table, project rebuilt & published to clear cache and all is good with both [Key] & [ExplicitKey] ( the latter in DapperContrib).



来源:https://stackoverflow.com/questions/33264891/dapper-simplecrud-insert-update-get-fails-with-message-entity-must-have-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!