【发布时间】:2011-12-04 14:45:49
【问题描述】:
我使用的是 Entity Framework 4.1 Code First,并且我有一个具有 IDENTITY 键的表,因为该表中的所有新条目都应该有一个自动生成的 ID(ID 列称为 AccountNumber)。我需要从该系统的前一个版本导入一些数据 - 这些帐号需要保留。
在a previous question 中,我了解到我必须设置 IDENTITY_INSERT ON 才能保留旧帐号。这个想法是,在导入老客户时,我将打开 IDENTITY_INSERT,运行原始 SQL 插入语句,然后将其关闭并使用 EF 实体正常进行。
所以,我有以下代码:
public const string InsertQuery = "INSERT INTO dbo.Businesses (AccountNumber, Name, Active, CreatedBy, CreatedOn, ModifiedBy, ModifiedOn) VALUES({0}, {1}, {2}, {3}, {4}, {5}, {6})";
...
dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Businesses ON");
dbContext.Database.ExecuteSqlCommand(InsertQuery, customerData.AccountNumber, customerData.Name, customerData.Active,
m_userContextManager.GetCurrentUserName(), Now,
m_userContextManager.GetCurrentUserName(), Now);
dbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Businesses OFF");
// load the entity and map the rest of the attributes
dbContext.SaveChanges();
当我开始执行第二条语句时,我收到了以下令人发指的错误(因为我刚刚将其设置为 OFF 左右):
Cannot insert explicit value for identity column in table 'Businesses' when IDENTITY_INSERT is set to OFF.
该语句的返回值为-1,但因为the documentation on MSDN for ExecuteSqlCommand 确实不够用,我不知道这意味着什么。如果语句由于某种原因失败,我希望会引发异常。有谁知道这里发生了什么?
【问题讨论】:
标签: entity-framework ef-code-first