简体   繁体   中英

Code first, using a non-sequential Id

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM