如何在EF Code First中临时关闭IDENTITY列? [英] How do I temporarily turn off an IDENTITY column in EF Code First?

查看:349
本文介绍了如何在EF Code First中临时关闭IDENTITY列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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 ,将密钥定义为未生成。

  • 使用更适合数据转换的其他技术,如SSIS


  • 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆