Entity Framework Core Error: Unable to track an entity of type "Model Class Object" because primary key property 'id' is null

Question: How do you resolve the Entity Framework Error: Unable to track an entity of type "Model Class Object" because primary key property 'id' is null?


Please Login to see the rest of the answer

Answer: Make sure you mark the Id of your class Model as the primary key using System.ComponentModel.DataAnnotations . This lets the Entity Framework know that the column is a primary key therefore it should have a value generated on the database site. 

using System.ComponentModel.DataAnnotations;

namespace FolderYourModelsAreLocated.Models
{
    public partial class YourModelName
    {
         [Key]
        public string id { get; set; }
}
}
  • In some cases, you might need to explicitly define in your DatabaseContext class that the Id column value should be generated at the database side. This is accomplished by adding ValueGeneratedOnAdd() function after the entity.Property id defined.
  • This might also cause an error that says: SqlExeption: Cannot insert explicit value for identity column in table "Table Name" when IDENTITY_INSERT is set to OFF.

Write an Article

Entity Framework Core Error: Unable to track an entity of type "Model Class Object" because primary key property 'id' is null

Edited Version 2

Question: How do you resolve the Entity Framework Error: Unable to track an entity of type "Model Class Object" because primary key property 'id' is null?

Answer: Make sure you mark the Id of your class Model as the primary key using System.ComponentModel.DataAnnotations . This lets the Entity Framework know that the column is a primary key therefore it should have a value generated on the database site. 

using System.ComponentModel.DataAnnotations;

namespace FolderYourModelsAreLocated.Models
{
    public partial class YourModelName
    {
         [Key]
        public string id { get; set; }
}
}
  • In some cases, you might need to explicitly define in your DatabaseContext class that the Id column value should be generated at the database side. This is accomplished by adding ValueGeneratedOnAdd() function after the entity.Property id defined.
  • This might also cause an error that says: SqlExeption: Cannot insert explicit value for identity column in table "Table Name" when IDENTITY_INSERT is set to OFF.
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.


© 2022 - ErnesTech - Privacy