Auto-increment on partial primary key with Entity Framework Core

后端 未结 5 2057
野趣味
野趣味 2020-12-13 05:50

I have declared the following model using the EF Core fluent API:

modelBuilder.Entity()
    .HasKey(p => new { p.Name, p.Id });
5条回答
  •  天命终不由人
    2020-12-13 06:19

    Annotate the property like below

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    

    To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():

    builder.ForNpgsqlUseIdentityColumns();
    

    This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().

    postgres efcore value generation

提交回复
热议问题