use*_*702 7 c# sql-server dapper dapper-contrib
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
这是C#类:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
插入这样的数据时:
connection.Insert(new Foo()
{
Id = 1,
Name = "name 1"
});
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
无法将值NULL插入列'Id',表'FooDatabase.dbo.Foos'; 列不允许空值.INSERT失败.
按照惯例,Dapper正确地假设它Id是主键,但它错误地假设它是一个标识列.我如何表明它不是标识列?
您可以ExplicitKey根据此问题使用该属性.
public class Foo
{
[ExplicitKey]
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请注意,返回值不是插入项目的ID,因为它通常是在您调用时Insert,而是始终0.