How to create a new record in Entity Framework without specifying the primary key in its parameters?

Viewed 348

I have a webpage in my project where a person signs up to be a user. My controller then gets an api call from the frontend with the post values entered from the signup.

I am trying to create a new record in my database with that info, is there any way to create an object without specifying the primary key in the parameters? I obviously am not taking in the id from the user so I just want to create the object without the id.

Controller

// POST api/values
[HttpPost]
public void Post(string username, string password, string email, string role)
{
    Users user = new Users(username, password, email, role);
    _repository.CreateUser(user);
    _repository.SaveChanges();
}

Model:

using System.ComponentModel.DataAnnotations;

namespace IssueTracker.Models
{
    public class Users
    {
        [Key]
        public int id { get; set; }

        [Required]
        public string username { get; set; }

        [Required]
        public string password { get; set; }

        [Required]
        public string email { get; set; }

        [Required]
        public string role { get; set; }

        public Users(int id, string username, string password, string email, string role)
        {
            this.id = id;
            this.username = username;
            this.password = password;
            this.email = email;
            this.role = role;
        }

        public Users()
        {
        }
    }
}
2 Answers

If your table in SQL Server is defined to have an Id INT IDENTITY column - then yes, SQL Server will handle creating the new PK automatically. You'll need to add another attribute to your Id column in your model:

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

    [Required]
    public string username { get; set; }

    // other properties here .....
}

This tells EF that the SQL Server database will handle creating a new unique value for Id which will be used as the primary key for your User object.

Related