【问题标题】:Using Dapper.Contrib InsertAsync returning 0 as Id on a class that has ExplicitKey attribute on Id在 Id 上具有 ExplicitKey 属性的类上使用 Dapper.Contrib InsertAsync 返回 0 作为 Id
【发布时间】:2021-03-17 19:22:27
【问题描述】:
    public class Customer
    {
        [ExplicitKey]
        public int Id { get; set; }

        [Write(false)]
        public string FullName { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string EmailToRevalidate { get; set; }
        public string SystemName { get; set; }
        public int BillingAddress_Id { get; set; }
..................
..................
        public int Add(Customer customer)
        {
            using (IDbConnection conn = Connection)
            {
                var result = conn.InsertAsync(customer).Result; // need to fix this it is return 0 because of the explicitkey attribue on ID.
                return result;
            }
        }

我希望 Add() 方法返回实际输入的 Id,即在客户对象中。否则我想返回整个对象。但我需要知道插入是否成功。

有没有办法检查 InsertAsync() Success = true 吗??

【问题讨论】:

  • 如果您决定退回到 Dapper(绕过 Contrib),this 可能会有所帮助。是在 MS Access 的上下文中,但基本原理还是一样的。

标签: c# .net insert dapper


【解决方案1】:

这是因为您使用了ExplicitKey。来自Github page

  • [ExplicitKey] - 此属性表示数据库不会自动生成的显式身份/密钥。

Dapper.Contrib 使用 SCOPE_IDENTITY 来获取 id,因此该列需要是 IDENTITY 列。 “正常” INSERT 不会返回任何内容,因此无法取回 Id。 您可以根据 SQL 方言对 SQL 执行不同的技巧,但如果您需要更改查询,则不会是 Dapper.Contrib。

如果您使用 KeyIDENTITY 列,它应该可以直接使用。

编辑: 如果要检查成功,只需检查异常。如果 INSERT 不成功会抛出异常。

【讨论】:

  • 我需要使用 [ExplicitKey] 因为我正在传递我自己的身份。如果我使用 [Key] 它会抛出错误“无法为 Id 插入值 NULL”
  • 对不起,我没有解释清楚。我试图传达,你想要的东西是不可能的。插入没有返回任何内容。如果您使用 IDENTITY Dapper.Contrib 将为您选择 SCOPE_IDENTITY,但这是一个极端情况。不管怎样,你有 ID,因为你自己传递了它。
  • 是的,我已经有了 ID。首先,我只是希望该方法返回 0 以外的值以实际确认它已经成功。现在我只需要在使用范围之外返回一个布尔值设置结果,并使用 tryCach 来返回结果是否成功
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 2021-11-24
  • 2019-12-01
相关资源
最近更新 更多