GORM 和 SQL 服务器:自动增量不起作用

GORM and SQL Server: auto-incrementation does not work

我正在尝试使用 GORM 将新值插入到我的 SQL 服务器 table 中。但是,它不断返回错误。您可以在下面找到详细示例:

type MyStructure struct {
    ID                     int32                    `gorm:"primaryKey;autoIncrement:true"`
    SomeFlag               bool                     `gorm:"not null"`
    Name                   string                   `gorm:"type:varchar(60)"`
}

执行下面的代码(创建内部事务)

myStruct := MyStructure{SomeFlag: true, Name: "XYZ"}

result = tx.Create(&myStruct)
    if result.Error != nil {
        return result.Error
    }

导致以下错误:

Cannot insert the value NULL into column 'ID', table 'dbo.MyStructures'; column does not allow nulls. INSERT fails

SQL GORM 生成的查询如下所示:

INSERT INTO "MyStructures" ("SomeFlag","Name") OUTPUT INSERTED."ID" VALUES (1, 'XYZ')

另一方面,直接在数据库连接上执行创建(不使用事务)导致以下错误:

Table 'MyStructures' does not have the identity property. Cannot perform SET operation

SQL GORM 生成的查询如下所示:

SET IDENTITY_INSERT "MyStructures" ON;INSERT INTO "MyStructures" ("SomeFlag", "Name") OUTPUT INSERTED."ID" VALUES (1, 'XYZ');SET IDENTITY_INSERT "MyStructures" OFF;

在这种情况下如何使自动递增工作? 为什么根据是内部交易还是外部交易,我会得到两个不同的错误?

我在 gorm 的问题中发现了这个:

gorm.DefaultCallback.Create().Remove("mssql:set_identity_insert")

https://github.com/go-gorm/gorm/issues/941#issuecomment-250267125

只需替换您的结构

type MyStructure struct {
    ID                     int32                    `gorm:"primaryKey;autoIncrement:true"`
    SomeFlag               bool                     `gorm:"not null"`
    Name                   string                   `gorm:"type:varchar(60)"`
}

有了这个

type MyStructure struct {
    ID                     int32                    `gorm:"AUTO_INCREMENT;PRIMARY_KEY;not null"`
    SomeFlag               bool                     `gorm:"not null"`
    Name                   string                   `gorm:"type:varchar(60)"`
}

最好将 gorm.Model 嵌入到默认提供字段的结构中:ID、CreatedAt、UpdatedAt、DeletedAt。 ID默认为主键,自增(由GORM管理)

type MyStructure struct {
    gorm.Model
    SomeFlag               bool                     `gorm:"not null"`
    Name                   string                   `gorm:"type:varchar(60)"`
}

删除现有的 table:db.Migrator().DropTable(&MyStructure{}) 并再次创建 table:db.AutoMigrate(&MyStructure{}) 然后尝试插入记录。