繁体   English   中英

在 Sql 服务器中使用 BYTE 作为标识列类型时,EF 核心“无法为标识列插入显式值”

[英]EF core "cannot insert explicit value for identity column" when using BYTE as identity column type in Sql Server

在程序启动期间,我无法使用 EF Core 将数据播种到 SQL 数据库中。

我有一个这样定义的 EF Core 表:

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

这是匹配的实体 class:

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

但是我不断收到以下错误:

迁移或植入数据库时发生错误。

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

Microsoft.Data.SqlClient.SqlException (0x80131904):当 IDENTITY_INSERT 设置为 OFF 时,无法在表“PoolStyles”中插入标识列的显式值。

该错误之前是 SQL EF Core 尝试运行:

失败:Microsoft.EntityFrameworkCore.Database.Command[20102] 执行 DbCommand (11ms) 失败 [Parameters=[@p0='?' (大小 = 1) (DbType = 字节), @p1='?' (大小 = 4000),@p2='?' (大小 = 4000),@p3='?' (大小 = 4000),@p4='?' (DbType = Boolean), @p5='?' (大小 = 4000),@p6='?' (Size = 1) (DbType = Byte)], CommandType='Text', CommandTimeout='30'] SET NOCOUNT ON; 插入 [PoolStyles]( [Id] 、[Code]、[Description]、[Icon]、[IsRestricted]、[Name]、 [Priority] )值(@p0、@p1、@p2、@p3、@p4 , @p5, @p6);

问题:您可以看到 EF Core 正在将[Id][Priority]列添加到已执行的 SQL 中,但这些值未包含在我尝试传递给SaveChangesAsync() ZC1945DAB508E166Z 的 object 中。

另外,我没有使用注释,所以不能使用它们来解决这个问题,我“手动编码”迁移,因为我需要的东西很复杂。

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

问题是使用字节作为标识列的数据类型。 我不知道为什么我知道我可以在 sql 服务器中手动创建一个类型为byte的标识列。 EF Core 中的某些东西令人窒息。

解决方案:

我将标识列数据类型更改为int ,并且插入可以与自动递增的 id 值一起正常工作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM