title: Turning off identity temporary - Entity Framework 4.1 Code First
body: <p>I'm having a issue with ID being created again when I import data into the database that has a different ID. All the data imports correctly, its just that the identity (ID column) needs to be what the import is.</p>
  
  <p>We have two keys in this model; ID and Identity. Identity is basically a unique instance name from the other datasource, so this will create an unique combination.</p>
  
  <p>This is all set via the OnModelCreating on the DatabaseContext which is from class DbContext:</p>
  
  <pre><code>        modelBuilder.Entity&lt;Observation&gt;().HasKey(m =&gt; new {m.Instance, m.Id});
          modelBuilder.Entity&lt;Observation&gt;().Property(m =&gt; m.Id).HasDatabaseGeneratedOption(
              DatabaseGeneratedOption.Identity);
  </code></pre>
  
  <p>The class looks like this:</p>
  
  <pre><code>public class Observation
  {
      public string Instance { get; set; }
      public int Id { get; set; }
      ...
  }
  </code></pre>
  
  <p>The database context is only created once in this ASP.Net MVC 3 Application with Ninject.</p>
  
  <p>I tried using a SQL  command to set identity off while adding a new entry, but with no success:</p>
  
  <pre><code>    public void SetIdentiyObservation(bool isOn)
      {
          var state = isOn ? "ON" : "OFF";
          _context.Database.SqlQuery&lt;Observation&gt;("SET IDENTITY_INSERT Observation @state", new SqlParameter("state", state));
      }
  </code></pre>
  
  <p>The created table structure looks like this in MSSQL:</p>
  
  <pre><code>CREATE TABLE [dbo].[Observations](
  [Instance] [nvarchar](128) NOT NULL,
  [Id] [int] IDENTITY(1,1) NOT NULL,
      ...
  PRIMARY KEY CLUSTERED 
  (
  [Instance] ASC,
  [Id] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]
  </code></pre>
  
  <p>Any help on this is appreciated :)</p>