在 SQL Server 中使用 BYTE 作为标识列类型时的 EF 核心"cannot insert explicit value for identity column"



在程序启动期间,我在使用EF Core将数据播种到SQL数据库中时遇到问题。

我有一个EF核心表定义如下:

migrationBuilder.CreateTable(
name: "PoolStyles",
columns: table => new
{
Id = table.Column<byte>(type: "tinyint", nullable: false)
.Annotation("SqlServer:Identity", "1,1"),
Name = table.Column<string>(type: "nvarchar(256)", maxLength: 256),
Code = table.Column<string>(type: "nvarchar(40)", maxLength: 40),
Description = table.Column<string>(type: "nvarchar(MAX)", nullable: true),
IsRestricted = table.Column<bool>(type: "bit"),
Priority = table.Column<byte>(type: "tinyint", nullable: true, defaultValue: 0),
Icon = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_PoolStyles", x => x.Id);
});

这是匹配的实体类:

public class PoolStyle
{
public byte Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public bool IsRestricted { get; set; }
public byte Priority { get; set; }
public string Icon { get; set; }
public string Description { get; set; }
}

在我的应用程序启动期间,我试图将一些数据种子放入我的数据库中,如下所示:

if (!context.PoolStyles.Any())
{
context.PoolStyles.Add(new PoolStyle { Code = "SRV", Description = "Survival Pool", Icon = "", IsRestricted = false, Name = "Survival" });
await context.SaveChangesAsync();
}

然而,我不断得到以下错误:

迁移或设定数据库种子时出错。

微软。EntityFrameworkCore。DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。

微软。数据SqlClient。SqlException(0x80131904(:当identity_insert设置为OFF时,无法为表"PoolStyles"中的标识列插入显式值。

错误前面是SQL EF Core尝试运行的:

失败:Microsoft。EntityFrameworkCore。数据库司令部[20102]执行DbCommand(11ms(失败[参数=[@p0='?'(大小=1((DbType=Byte(,@p1='?'(尺寸=4000(,@p2='?',@p3="?"(大小=4000(,@p4='?'(DbType=Boolean(,@p5='?'(尺寸=4000(,@p6='?'(Size=1((DbType=Byte(],CommandType='Text',CommandTimeout='30']设置NOCOUNT;插入[PoolStyles]([Id]、[Code]、[Description]、[Icon]、[IsRestricted]、[Name]、[Priority]

问题:您可以看到EF Core正在向执行的SQL添加[Id][Priority]列,但这些值不包括在我试图传递给SaveChangesAsync()函数的对象中。

此外,我没有使用注释,所以不能使用这些注释来解决这个问题,我"手代码";迁移,因为我需要的东西很复杂。

问题:有人能帮我弄清楚EF Core为什么试图将这些值添加到insert语句中吗?

问题是使用字节作为标识列的数据类型。我不知道为什么,因为我知道我可以在sql server中手动创建类型为byte的标识列。EF Core中的某些东西正在窒息。

解决方案:

我将标识列数据类型更改为int,插入可以正确地使用自动递增的id值。

也许我错过了其他东西,但它起作用了,这些表不会有太多记录,所以我只使用int并继续,哈哈。

相关内容

最新更新