为什么此带有IDENTITY_INSERT的EF插入不起作用? [英] Why does this EF insert with IDENTITY_INSERT not work?
问题描述
这是查询:
using (var db = new AppDbContext())
{
var item = new IdentityItem {Id = 418, Name = "Abrahadabra" };
db.IdentityItems.Add(item);
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
db.SaveChanges();
}
执行后,插入的记录在新表上的Id
仍为1.
When executed, the Id
of the inserted record, on a new table, is still 1.
新:当我使用交易记录或TGlatzer的答案时,都会出现异常:
NEW: When I use either the transaction, or TGlatzer's answer, I get the exception:
必须为表项目"中的标识列指定显式值 当IDENTITY_INSERT设置为ON或复制用户为 插入到NOT FOR REPLICATION身份列中.
Explicit value must be specified for identity column in table 'Items' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
推荐答案
绝对不能在生产代码中使用,只是为了好玩
我仍然认为我的答案仍然是我的答案,请不要使用此答案(以解决此问题),请查看下面的其他答案
我不建议这样做,因为这是一个疯狂的黑客,但是无论如何.
I do not suggest this because it is a crazy hack but anyway.
我认为我们可以通过拦截SQL命令并更改命令文本来实现它
(您可以从DbCommandInterceptor继承并覆盖ReaderExecuting)
I think we can achieve it by intercepting the SQL command and changing the command text
(you can inherit from DbCommandInterceptor and override ReaderExecuting)
我目前没有一个可行的例子,我必须走,但我认为这是可行的
I don't have a working example at the moment and I have to go but I think it is doable
示例代码
public class MyDbInterceptor : DbCommandInterceptor
{
public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
if (is your table)
{
command.CommandText = "Set Identity off ,update insert into ,Set Identity off"
return;
}
base.ReaderExecuting(command, interceptionContext);
}
}
ORM是一个很好的抽象,我真的很喜欢它们,但我认为尝试破解"它们以支持较低(更接近db)级别的操作没有道理.
我尝试避免存储proc,但我认为在这种情况下(如您所说的例外),我认为您应该使用一个
ORMs are a nice abstraction and I really like them but I don't think it makes sense to try to "hack" them to support lower(closer to the db) level operations.
I try to avoid stored procs but I think in this (as you said exceptional) case I think you should use one
这篇关于为什么此带有IDENTITY_INSERT的EF插入不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!