doutou19761022 2016-10-21 13:40
浏览 137

如何为GORM关闭IDENTITY_INSERT

I would like to turn OFF the IDENTITY_INSERT to insert data with GORM without specify any ID.

I try this :

func main() {

    db, err := gorm.Open("mssql", "...")

    //...
    db.DropTable(&User{})
    db.CreateTable(&User{})
    db.Exec("SET IDENTITY_INSERT users OFF;") <-- this doesn't work

    for _, user := range users {
        db.Create(&user)
    }

}

type User struct {
    ID        uint
    UserName  string
    FirstName string
    LastName  string
}

var users []User = []User{
    User{UserName: "testUserName", FirstName: "testFirstName", LastName: "TestLastName"},
    User{UserName: "testUserName", FirstName: "testFirstName", LastName: "TestLastName"},
    User{UserName: "testUserName", FirstName: "testFirstName", LastName: "TestLastName"},
}

EDIT :

The data is not create in database, I have the following error (sorry in french) :

(mssql: Une valeur explicite doit être spécifiée dans la colonne d'identité de la table 'users' quand IDENTITY_INSERT est défini à ON, ou qu'un utilisateur de la réplication effectue une insertion dans une colonne d'identité NOT FOR REPLICATION.)

in en :

Cannot insert explicit value for identity column in table 'users' when IDENTITY_INSERT is set to OFF."

The program work if I add the ID value like :

User{ID: 1, UserName: "testUserName", FirstName: "testFirstName", LastName: "TestLastName"}

Someone have any idea ?

  • 写回答

1条回答 默认 最新

  • dongliechuich10319 2016-10-21 13:58
    关注

    If you really need to do this, and there are rare cases for this you have to enable this functionality ( to set the value for identity column ) like so

    Set Identity_Insert dbo.users On
    Insert Into users (YOURIDENTITYCOLUMN, NAME)
    Values(1, 'your value')
    Set Identity_Insert dbo.users Off
    

    If your not trying to set the value of the identity column, then remove the statement SET Identity_Insert dbo.users Off portion from your query.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line