2

I have an ASP.NET Core project. I am using the database first approach with SQL Server and generated my models using EF Core.

I want the primary key to be auto incremented. Everything seems to work fine on the first entry in which it defaults my primary key (PimId) to 0. However, on the second insertion, the primary key remains 0.

My onModelCreate function

modelBuilder.Entity<ImportPim>(entity =>
        {
            entity.HasKey(e => e.PimId);
            entity.ToTable("Import_PIM");

            entity.Property(e => e.PimId)
                .HasColumnName("PIM_Id")
                .ValueGeneratedNever();

            entity.Property(e => e.CliId).HasColumnName("CLI_Id");

            entity.Property(e => e.PimAccountNumber)
                .HasColumnName("PIM_AccountNumber")
                .HasMaxLength(50)
                .IsUnicode(false);

This was generated by EF Core, I have tried changing ValueGeneratedNever() to ValueGeneratedOnAdd() but I get a saving error in SQL Server.

Any suggestions on how to do?

4
  • don't you need to add ValueGenerationOnAdd instead of ValueGeneratedNever Commented Dec 14, 2020 at 18:25
  • Does your table column have IDENTITY(1,1)? I generate models from databases, and usually the identity key property doesn't need to be specified in OnModelCreating Commented Dec 14, 2020 at 18:26
  • 1
    It is useless change it in OnModelCreating since you are using DB first. You need to set the primary key AUTO_INCREMENT in sql server, then re-generate the models. Commented Dec 15, 2020 at 6:44
  • @mj1313 an insane Thanks. It seems like the onModelCreating does not have any effect if you're using the DB first approach. Commented Dec 15, 2020 at 9:36

2 Answers 2

1

ValueGeneratedOnAdd() should works. If not, make sure that you set Identity for PimId in your table in SQL Server.

    entity.Property(e => e.PimId)
        .HasColumnName("PIM_Id")
        .ValueGeneratedOnAdd();
Sign up to request clarification or add additional context in comments.

Comments

0

You can set it as identity (Auto increment) like this:

modelBuilder.Entity<ImportPim>().Property(entity => entity.PimId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

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.