Unable to track an entity of type "TEntity" because primary key property 'id' is null. How to resolve it?

quoctuan.cqt@gmail.com | 343 day | 849


Asp.net Core 3.0 and Entity Framework Core 3.0 have been released for a long time ago. There are many changes in those. Today, I wanna discuss with you one of the most issues when we migrate to version 3.0. This is the issue when we execute Add/Update/Delete on our entity. (For more detail, you can take a look on official document here)

I have an Entity model Client with Primary Key is "Id".

 public class Client
    {
        public string Id { get; set; }
        public string ClientPhone { get; set; }
        public string ClientEmail { get; set; }
        public string ClientAddress { get; set; }
        public bool IsVerifyUser { get; set; }
        public ClientStatus ClientStatus { get; set; }
        public bool IsSystem { get; set; }
    }

In your repository, we have Add() method to create new Entity into Database:

 public virtual void Add(TEntity entity)
 {
       _context.Set<TEntity>().Add(entity);
       _context.SaveChange();
 }

If you run this method in EF 3.0, you will get an error like this:

"Unable to track an entity of type "TEntity" because primary key property 'id' is null"

To resolve this, you just do a small change in your DbContext:

public class DemoContext : DbContext
    {
        public DemoContext(DbContextOptions options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Client>(entity =>
            {
                entity.HasKey(x => x.Id);
                entity.Property(x => x.Id).ValueGeneratedOnAdd();
            });

            .....

            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<Client> Clients { get; set; }

        .....
    }

Easy!!!? Hopefully, this saves your time.

 

Top Articles

Bất Đầu Với WebApi Và Dot Net Core (.Net Core)

1276 day
Butter Ngo
Views 8930
Comments 0

Dot Net Core Bearer Token With (JWT) (.Net Core)

1208 day
Butter Ngo
Views 5557
Comments 0

Repository Và Unit Of Work (Entity Framework)

1195 day
ndtung449@gmail.com
Views 5038
Comments 0

Bắt Đầu Với Dot NET Core (.Net Core)

1287 day
Butter Ngo
Views 4424
Comments 0

Top Question

Bi lỗi Invalid Column Name khi sử dụng LinQ (.Net)

1135 day
Bảo Dương
Views 1337
Answers 2

.NET CORE API JWT (.Net Core)

428 day
huynhminhnhut97@gmail.com
Views 939
Answers 2

Làm thế nào để lấy information từ token (.Net Core)

525 day
ngovu.dl@gmail.com
Views 850
Answers 1