gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:16:04 24 4
gpt4 key购买 nike

我正在尝试使用 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"
});

我收到以下错误:

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; }
}

请注意,返回值不是插入项的 ID,因为它通常是调用 Insert 时的值,而是始终为 0 .

关于c# - 当主键列不是标识列时,如何插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40217705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com