首页 > 解决方案 > 无法跟踪“Entity”类型的实体,因为其主键属性“Id”为空

问题描述

public clase Book
{
  [Key]
  public string Id{get;set;}
  public string Name{get;set;}
  ...
}
_dbContext.Books.Add(new Entity(){
   Name="C#10.0",
   ....
})
_dbContext.SaveChanges()

异常消息:System.InvalidOperationException:无法跟踪“Book”类型的实体,因为其主键属性“Id”为空。

在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap`1.Add(InternalEntityEntry entry) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)

When I use this DatabaseGeneratedAttribte, after assigning a value to the primary key in the application, call "SaveChanges()" an exception will be thrown and the trace will be modified.

我希望在为主键分配一个值之后,这个值会占上风。如果没有赋值,则可以自动生成该值。

标签: entity-framework-core

解决方案


如果您希望自动生成 Id 参数,请确保ValueGeneratedOnAdd()在 ModelCreating 方法中应用该参数:

protected override void OnModelCreating(ModelBuilder builder)
{
            builder.Entity<Book>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedOnAdd();
            });
}

否则,您应该在将书籍实体添加到 DB 之前为 Id 分配适当的值。


推荐阅读