0

I have a code first project with a few tables, I am trying to determine that for a certain object the Id with which it will be inserted will not be the sequential Id that sql provides but an Id i will provide.

Although the code in my repository is creating the object properly and assigns it the wanted Id once it is inserted to my DB in the:

DbContext.Set<Containers>().Add(entity);

It is inserted as the next sequential Id.

In my code first the Id column for the base Entity from which all my entities derive is:

public int Id { get; set; }

I am looking the change to the Id's only in this entity. Any suggestions?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Ravid Goldenberg
  • 2,119
  • 4
  • 39
  • 59
  • Possible duplicate of [Entering keys manually with Entity Framework](http://stackoverflow.com/questions/18907411/entering-keys-manually-with-entity-framework) – Rob Oct 18 '15 at 09:42
  • And another non-SO solution: http://cloudonedesign.com/Blog/Post/ef-code-first-disabling-identity-for-int-primary-k-17 – Rob Oct 18 '15 at 09:42
  • Not sure how you would do this in EF but you need to set a unique index property rather than an identity key – Peter Smith Oct 18 '15 at 09:46
  • The slightly complicating factor here is the base class. And that is a suspect design when one or more derived classes have a different key policy. – H H Oct 18 '15 at 09:47
  • A link from the first comment above might be useful. [See](http://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/) – Peter Smith Oct 18 '15 at 09:50

1 Answers1

1

this is the default behavior: when you don't alter it explicitly, EF will create an autoincrement column on the ID, if it's type is fitting.

To alter it, use Fluent API:

modelBuilder.Entity<Containers>().Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

or Data annotations:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

Maybe you'll have to run an migration after this to alter the table to non-autoincrement also. If you don't want to do that, you'll have to use Identity insert, wrapped in a transaction, every time you want this behavior.

DevilSuichiro
  • 1,049
  • 8
  • 21