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?


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.

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.
Entity Framework
published
v.0.01





For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]