使用 Typeorm EntityManager API 将数字 id 插入主键列

Insert number id into primary key column using Typeorm EntityManager API

我正在尝试使用 Typeorm 将数字 ID 插入到用户 table 的主列中以构建 graphql 解析器,但出现错误

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

我试过 set identity_insert on,但没成功

await em.query("SET IDENTITY_INSERT User ON")
await em.create(User, newUser)

网上有人建议把这两个查询结合起来,但我不知道在Typeorm中如何实现。 我知道可以编写原始查询来组合它们。请问有什么好的方法吗?

您需要在事务内执行命令。

const em = getManager();
await em.transaction(async transactionalEntityManager => {
    await transactionalEntityManager.query("SET IDENTITY_INSERT User ON");
    await transactionalEntityManager.create(User, newUser);
    await transactionalEntityManager.query("SET IDENTITY_INSERT User OFF");
});

不幸的是,我的解决方案是写原始 sql:

await em.query("SET IDENTITY_INSERT User ON;" + 
"insert into user(id, firstname, lastname, username, password) " +
"values(@0, @1, @2, @3, @4)", [variables...]

希望这个解决方案可以帮助使用 Typeorm 和 MS SQL 服务器的人。