Code-First Entity Framework inserting data with custom ID

岁酱吖の 提交于 2019-12-09 17:21:42

问题


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?


回答1:


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);



回答2:


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");
        }
    }


来源:https://stackoverflow.com/questions/12728226/code-first-entity-framework-inserting-data-with-custom-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!