Setting a primary key that generated identically and automatically in EF Core

I created an entity called Student

public class Student
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }

} 

When Required attribute is added to Id property, I have to input a value for Id. I want to generate Id property automatically and identity via EF Core.

  static void Main(string[] args)
  {
      var db = new AppDbContext();
      db.Add(new Student { Name = "Peter" });
      db.SaveChanges();
  }

If I add DatabaseGenerated attribute, Does Id become the primary key?

How can I define a primary key that automatically generated and I do not have to set the key value for it?

>Solution :

You can specify the primary key using the [Key] attribute. It can be defined with your identity as:

public class Student
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }

} 

Leave a Reply