16

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

使用此脚本创建数据库表:

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# 类:

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

    public string Name { get; set; }
}

像这样插入数据时:

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

我收到以下错误:

无法将值 NULL 插入到列“Id”、表“FooDatabase.dbo.Foos”中;列不允许空值。插入失败。

按照惯例,Dapper 正确地假定这Id是主键,但它错误地假定它是一个标识列。如何表明它不是标识列?

4

1 回答 1

18

您可以ExplicitKey根据此问题使用该属性。

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

    public string Name { get; set; }
}

请注意,返回值不是插入项目的 id,因为它通常是调用时Insert的值,而是 always 0

于 2016-10-24T12:11:17.790 回答