如何在EF Code First中临时关闭IDENTITY列? [英] How do I temporarily turn off an IDENTITY column in EF Code First?
问题描述
public class Business:EntityBase
{
[Key,DatabaseGenerated (DatabaseGeneratedOption.Identity)]
public int AccountNumber {get;组; }
现在,导入的记录需要保留他们的 AccountNumber
旧系统的值。但是,新值应使用数据库生成的 IDENTITY
值。
如何关闭 IDENTITY
当我导入旧的记录,然后在应用程序生命周期的剩余时间内重新打开它?在导入记录之前执行此操作无效:
context.Database.ExecuteSqlCommand(set identity_insert Businesses on);
你不能。执行 set identity_insert
命令更改SQL Server的行为,而不是实体框架的行为。
您有使用原始的ADO.NET命令(而不是实体)或 ExecuteSqlCommand
。
DbContext
,将密钥定义为未生成。I'm creating a rewrite of an existing application in EF Code First, but I need to import some of the data from the existing application's database. Here's the definition of my entity class:
public class Business : EntityBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AccountNumber { get; set; }
Now, the imported records need to retain their AccountNumber
value from the old system. However, new values should use the IDENTITY
value generated by the DB.
How do I turn off the IDENTITY
while I'm importing old records, then turn it back on for the remainder of the lifetime of the application? Executing this before importing the records has no effect:
context.Database.ExecuteSqlCommand("set identity_insert Businesses on");
You can't. Executing a set identity_insert
command changes the behavior of SQL Server, but not the behavior of Entity Framework.
You have three choices for importing records:
- Use raw ADO.NET commands (not entities) or
ExecuteSqlCommand
. - Use a different
DbContext
, in which you define the keys as non-generated. - Use a different technology that's more suited for data conversion, like SSIS
这篇关于如何在EF Code First中临时关闭IDENTITY列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!