EF 7 身份插入问题 [英] EF 7 Identity Insert Issue
问题描述
我必须能够设置要添加到列表final_zones"中的实体的主键.我有一个控制器构造函数,如下所示:
I have to be able to set the primary key of the entities I am trying to add in my list "final_zones". I have a controller constructor as follows:
public UtilController(CFETSContext context)
{
_context = context;
}
......Then in a web api method.........
using (var transaction = _context.Database.BeginTransaction())
{
_context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON");
_context.SaveChanges();
transaction.Commit();
}
using (var transaction = _context.Database.BeginTransaction())
{
_context.Zones.AddRange(final_zones);
_context.SaveChanges(); //ERROR HERE
transaction.Commit();
}
无论我做什么,我似乎都无法打开 IDENTITY_INSERT.我收到以下错误:
No matter what I do, I cannot seem to get IDENTITY_INSERT to turn on. I get the following error:
{"Cannot insert explicit value for identity column in table 'Zone' when IDENTITY_INSERT is set to OFF."}
我似乎无法关闭它.我可以在控制器中将实体添加到我的数据库中,所以我知道其他一切都在工作.我也尝试过在没有事务的情况下执行此操作,结果相同.
I just can't seem to get it to turn off. I can add entities to my DB in the controller, so I know everything else is working. I have tried doing this without a transaction as well with the same result.
_context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON");
_context.Zones.AddRange(final_zones);
_context.SaveChanges();
有什么想法吗?我不知道接下来要尝试什么.谢谢.
Any ideas? I am at a loss for what to try next. Thanks.
推荐答案
我用以下方法解决了:
using (var dbContextTransaction = _context.Database.BeginTransaction())
{
try
{
_context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON");
_context.Zones.AddRange(final_zones);
_context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception e)
{
dbContextTransaction.Rollback();
}
}
注意:您必须每张桌子都这样做.IDENTITY_INSERT 似乎一次只能为 1 个表设置,因此您可以这样做或在同一事务中将其切换为 OFF.
NOTE: You HAVE to do this per table. IDENTITY_INSERT can only be set for 1 table at a time it seems, so you can do it this way or toggle it to OFF in the same transaction.
此外,IDENTITY_INSERT 必须在事务中,因为它只在事务期间保持打开状态.
Also, IDENTITY_INSERT has to be in a transaction, as it only stays on for the duration of a transaction.
这篇关于EF 7 身份插入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!