Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }

} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading