Code-First Entity Framework inserts data with user identifier

I use EF with the code first in my project and face problem when data with a user id is inserted.

When I try to insert data with a user identifier (for example, 999), EF ignores it and inserts an indexed identifier into the table.

My model:

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

How to solve this problem?

EDIT:

1) How to start an increment from N, but not from 0?

2) If I do not specify a user identifier, the DB must increment and insert its own. If I specify a special identifier, DB should insert it. Is it possible?

+7
source share
2 answers

you can use the following attribute

 [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] 

to the key to your class or using fluentAPI

 modelBuilder.Entity<Address>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 
+19
source

This is valid in OnModelCreating in the DbContext class. You can customize the sequence. for a start and increase. As you wish, adding the following to the DbContext class 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"); } } 
0
source

All Articles