当主键列不是标识列时,如何插入数据?

How do I insert data when the primary key column is not an identity column?

我正在尝试使用 Dapper.Contrib 在主键列不是标识列的 table 中插入数据。

数据库 table 是使用此脚本创建的:

begin transaction

create table
    dbo.Foos
    (
        Id int not null,
        Name nvarchar(max) not null
    )
go

alter table
    dbo.Foos
add constraint
    PK_Foos primary key clustered
    (
        Id
    )

go

commit

这是 C# class:

public class Foo
{
    public int Id { get; set; }

    public string Name { get; set; }
}

像这样插入数据时:

connection.Insert(new Foo()
{
    Id = 1,
    Name = "name 1"
});

我收到以下错误:

Cannot insert the value NULL into column 'Id', table 'FooDatabase.dbo.Foos'; column does not allow nulls. INSERT fails.

Dapper 按照惯例正确地假设 Id 是主键,但它错误地假设它是一个标识列。我怎样才能表明它不是标识列?

您可以根据 this issue 使用 ExplicitKey 属性。

public class Foo
{
    [ExplicitKey]
    public int Id { get; set; }

    public string Name { get; set; }
}

请注意,return 值是 而不是 插入项目的 ID,因为它通常在您调用 Insert 时是 0.