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.
推荐答案
我用以下方法解决了这个问题:
I solved it with the following:
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屋!