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?

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.

Edit this Article
Entity Framework Error Technology published
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

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

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy