Dapper.SimpleCRUD插入/更新/获取失败,并显示消息“实体必须具有至少一个[Key]属性”。 [英] Dapper.SimpleCRUD Insert / Update / Get fails with message "Entity must have at least one [Key] property"

查看:123
本文介绍了Dapper.SimpleCRUD插入/更新/获取失败,并显示消息“实体必须具有至少一个[Key]属性”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Dapper的新孩子。尝试将CRUD操作与Dapper和Dapper.SimpleCRUD lib合并。这是示例代码...

我的数据模型看起来像

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实施-插入

Dapper Implementation - Insert

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

由于Db中的ProdId是身份列,因此失败。

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

Dapper实施-获取

Dapper Implementation - Get

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

这是一个例外:


实体必须至少具有一个[Key]属性!

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


推荐答案

之所以发生这种情况,是因为您使用的是Dapper扩展程序,该程序已实现了 Insert CRUD扩展方法。理想情况下,可以使用简单的

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实现。在Dapper中执行,但是由于要传递对象并通过扩展名自动创建一个插入查询,您需要帮助它理解,它是给定产品实体的主键,以下修改将有所帮助:

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;}

其中Key属性应在 Dapper扩展组件模型中实现。

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

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

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

这篇关于Dapper.SimpleCRUD插入/更新/获取失败,并显示消息“实体必须具有至少一个[Key]属性”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆