Code-First Entity Framework inserting data with custom ID
Asked Answered
C

3

11

I am using code-first EF in my project and face issue when the data with custom id is being inserted.

When I am trying to insert data with custom ID (for instance 999), EF ignores it and inserts incremented ID into table.

My model:

public class Address
{
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
...
}

How to solve this probleb?

EDIT:

1) How to begin incrementing from N, but not from 0?

2) If I don't specify custom ID, DB must increment and inserts own. If I specify custom ID, DB must insert it. Is it possible?

Chiu answered 4/10, 2012 at 13:20 Comment(2)
Do you want to remove the autoincrement function from your table overall?Kletter
No, I don't. If I don't specify custom ID, DB must increment and inserts own. If I specify custom ID, DB must insert it. Is it possible? Is it possible to begin incrementing from N, but not from 0?Chiu
W
21

you can use the following attribute

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]

on the key to your class or using fluentAPI

modelBuilder.Entity<Address>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Weisshorn answered 4/10, 2012 at 13:30 Comment(2)
Thanks for the answer. Is it possible use DatabaseGeneratedOption.Identity and inserting custom ID?Chiu
No as that would be indicating to EF that you want the Database to generate the id for you and EF will dutifully ignore any value you have set on that field.Weisshorn
R
1

In EF Core you can use:

builder.Property(x => x.Id).ValueGeneratedNever();

or

[DatabaseGenerated(DatabaseGeneratedOption.None)]
Rambler answered 5/3, 2020 at 10:47 Comment(0)
A
0

It's actually in the OnModelCreating in the DbContext class. You can setup a sequence no. to start from and incrementBy as you please by adding the following in the DbContext class Please see here for example: https://ef.readthedocs.io/en/staging/modeling/relational/sequences.html

  class MyContext : DbContext
    {
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
                .StartsAt(1000)
                .IncrementsBy(5);

            //Once a sequence is introduced, you can use it to generate values for properties in your model. For example, you can use Default Values to insert the next value from the sequence.
            modelBuilder.Entity<Order>()
                .Property(o => o.OrderNo)
                .HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
        }
    }
Ammonium answered 26/10, 2016 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.