Search code examples
c#asp.net-coreentity-framework-corerazor-pages

How to add new record in a table with a value for primary key?


I have a table User in my database using Entity Framework Core.

This is my class:

public class User
{
    [Key]
    public int Id { get; set; }  
    public string Title { get; set; } = "";
}

In this class, Id is the primary key, therefore, when I want to add a new record to database, this column is autoincrement.

_context.User.Add(MyUser);

But I want to set it manually and set the Id without autoincrement. I visited [this page][1] (which was similar to my question) but that isn't my question and I don't find my answer there. Thank you.


Solution

  • The default is auto increment. But it will also use your Id if you specify it (repeat Id will be exception, not include "0").
    If you want to totally disable auto-increment. you could add following attribute. Then you have to specify the ID on your own, or there will be exception.

    public class User
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)] // Prevents auto-increment
        public int Id { get; set; }
    }
    

    It can also be configured in DBContext like

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .Property(u => u.Id)
            .ValueGeneratedNever(); // Indicates the ID must be manually set
    }