How to tell Entity Framework that my ID column is auto-incremented (AspNet Core 2.0 + PostgreSQL)?

前端 未结 3 2109
生来不讨喜
生来不讨喜 2021-02-07 06:52

Code is simple. Tag.cs entity:

public partial class Tag
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { ge         


        
相关标签:
3条回答
  • 2021-02-07 07:13

    You have to use here "ValueGenerationOnAdd()". As the issue you are getting is already reported on GitHub. Please find the below link.

    https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/73

    You can find more info regarding Generated Value pattern from following link.

    Value generated on add

    public classs SampleContext:DBContext{
    public DbSet<Tag> Tag { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder){
        modelBuilder.Entity<Tag>()
            .Property(p => p.ID)
            .ValueGeneratedOnAdd();
     }
    public class Tag{
      public int Id { get; set; }
      public string Name { get; set; }
      public string Description{get;set;}
      }
    }
    

    Source:- https://www.learnentityframeworkcore.com/configuration/fluent-api/valuegeneratedonadd-method

    Hope this will help

    0 讨论(0)
  • 2021-02-07 07:16

    After a lot of wasted time on research I've solved it absolutely unexpected. Actually, the solution to my problem lies on the surface, because the problem is not in EF and not in it's stuff. In my case it was SEQUENCE. I mean, involved table has serial column and related sequence just was changed by some side-effect. In another words - sequence was restarted from 1 and at the same time the table is already having values with 1, 2, 3 ... etc. That's why postgres throws 'duplicate key' error. So, the solution is:

    ALTER SEQUENCE "your_table_seq" RESTART WITH your_value;
    
    0 讨论(0)
  • 2021-02-07 07:22

    According to the Postgre SQL docs here is an example which shows how to achieve the desired result:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
       => modelBuilder.Entity<Blog>().Property(b => b.Id).UseIdentityAlwaysColumn();
    
    0 讨论(0)
提交回复
热议问题