在 Id 上具有 ExplicitKey 属性的类上使用 Dapper.Contrib InsertAsync 返回 0 作为 Id

问题描述 投票:0回答:1
    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,即位于客户对象中的 Id。否则我想返回整个对象。但我需要知道插入是否成功。

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

c# .net insert dapper
1个回答
0
投票

这是因为您使用了

ExplicitKey
。来自 Github 页面

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

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

如果您使用

Key
IDENTITY
列,它应该可以开箱即用。

编辑: 如果你想检查是否成功,只需检查是否有异常即可。如果INSERT不成功将会抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.