【问题标题】:Unable to track an entity of type 'Entity' because its primary key property 'Id' is null无法跟踪“Entity”类型的实体,因为其主键属性“Id”为空
【发布时间】:2021-08-09 02:37:39
【问题描述】:
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 条目) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry 条目) 在 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.

我希望在给主键赋值后这个值占上风。如果不赋值,可以自动生成值。

【问题讨论】:

  • EntityFromeworkCore>=5.0 和 Pomelo.EntityFrameworkCore.MySql >= 5.0
  • 不确定我是否理解这个问题。 string 属性默认不是自动生成的。如果您想使其自动生成,请使用属性或 fluent API 进行配置。然后通过idea,如果您提供PK值,那么它将被使用,否则将自动生成。因此,由于 PK 不是自动生成的,因此您通常会显示出这种异常,因此您可以从问题中省略它。使用属性的确切问题是什么?
  • 你明白我的想法,问题如下 Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s),但实际上影响了0 row(s);自加载实体以来,数据可能已被修改或删除。有关理解和处理乐观并发异常的信息,请参阅go.microsoft.com/fwlink/?LinkId=527962。在 Microsoft.EntityFrameworkCore.Update.AffectedCountModificationCommandBatch.ThrowAggregateUpdateConcurrencyException(Int32 commandIndex,Int32
  • 嗯,你有一些流畅的配置,例如HasDefaultValueSql 的那个属性?问题是自动生成可能是客户端或数据库端。而 EF INSERT 命令行为取决于此。必须看看 Pomelo 对自动生成的字符串有什么作用——通常它们是自动生成的客户端,新的 Guid 转换为字符串。
  • 上面的错误是配置了ValueGeneratedOnAdd。如果配置能达到我的目的,那就完美了。我在柚子里咨询过。他们说应该是efcore。太可怕了。

标签: entity-framework-core


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢你的建议,但这不是我所期望的。我的想法是我提供PK值,然后它会被使用,否则会自动生成。
猜你喜欢
  • 2020-03-26
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2020-01-31
  • 2019-12-29
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多