IDENTITY_INSERT during seeding with EntityFramework 6 Code-First

后端 未结 9 728
遥遥无期
遥遥无期 2020-12-05 10:19

I have an entity that has an Auto-identity (int) column. As part of the data-seed I want to use specific identifier values for the \"standard data\" in my syste

9条回答
  •  天涯浪人
    2020-12-05 11:14

    Say you have a table named Branch with a column of type integer named BranchId. By convention with SQL Server, EF will assume that a column with of type integer is an Identity column.

    So it will automatically set the column's Identity Specification to:

    • (Is Identity) Yes
    • Identity Increment 1
    • Identity Seed 1

    If you want to seed an entity with id values that are assigned, then use the DatabaseGeneratedOption as follows:

    public class Branch
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int BranchId { get; set; }
        public string Description { get; set; }
    }
    

    You can then seed the data and assign whatever value you want to the BranchId.

提交回复
热议问题