9

It seems like the auto-increment function for PostgreSQL doesn't seem to work.

I have the following code:

namespace project.Models
{
   public class DatabaseModel
   {
       [Key]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       [Column(Order=1, TypeName="integer")]
       public int ID { get; set; }
   }
 }

When I update the database (after doing a migration) the ID column is the primary key without being a auto-increment.

When I try to add a new object to the database I get the following error:

Microsoft.EntityFrameworkCore.DbContext[1]
  An exception occurred in the database while saving changes.
  Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Npgsql.PostgresException: 23502: null value in column "ID" violates not-null constraint

Can anyone help solve this problem? How can I get the key to be auto-incremented?

3 Answers 3

11
[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 DBContext's OnModelCreating() event handler:

protected override void OnModelCreating(ModelBuilder builder) 
{
    builder.ForNpgsqlUseIdentityColumns();
}

This will assure all keys and other properties which have ValueGeneratedOnAdd() use 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

Sign up to request clarification or add additional context in comments.

1 Comment

Just a quick note that presently Entity Framework does not require (nor supports) this pattern: learn.microsoft.com/en-us/ef/core/modeling/…
5

Because you created the column with the specific type integer you need to specify the type as serial for PostgreSQL to generate the id for you.

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

1 Comment

This is no longer the case. PostgreSQL for EFCore now natively supports identity columns. npgsql.org/efcore/modeling/generated-properties.html
1
 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.UseSerialColumns();

    }

You should use this in your DbContextClass to create auto incremented value for primary key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.