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 ??
这是因为您使用了
ExplicitKey
。来自 Github 页面:
Dapper.Contrib 使用 SCOPE_IDENTITY 来获取 id,因此该列需要是 IDENTITY 列。 “正常”插入不会返回任何内容,因此无法取回 Id。 您可以根据 SQL 方言对 SQL 执行不同的技巧,但如果您需要更改查询,则不会是 Dapper.Contrib。
如果您使用
Key
和 IDENTITY
列,它应该可以开箱即用。
编辑: 如果你想检查是否成功,只需检查是否有异常即可。如果INSERT不成功将会抛出异常。