6

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

4

2 回答 2

12

发生这种情况是因为您使用的是实现了InsertCRUD 扩展方法的 Dapper 扩展。理想情况下,这可以使用简单的来实现

con.Execute在 Dapper 中,但是由于您想通过扩展自动传递对象并创建插入查询,因此您需要帮助它理解,这是给定产品实体的主键,以下修改将有所帮助:

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

其中 Key 属性应在Dapper ExtensionComponent Model.

或者,您可以重命名prodIdId,这将自动使其成为密钥。还要检查以下链接,您可以在其中为实体创建单独的映射器,从而定义密钥,无论您的情况如何

于 2015-10-21T17:49:30.370 回答
1

连接到 SQL Server 2016 时,当我忘记将主键附加到表的 Id 列时,Dapper.Contrib 和 Dapper.SimpleCRUD 都出现此错误。

主键添加到表中,项目重建和发布以清除缓存,并且 [Key] 和 [ExplicitKey] (后者在 DapperContrib 中)都很好。

于 2015-12-15T18:59:33.277 回答