entity-framework-core - 无法跟踪“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.
我希望在为主键分配一个值之后,这个值会占上风。如果没有赋值,则可以自动生成该值。
解决方案
如果您希望自动生成 Id 参数,请确保ValueGeneratedOnAdd()
在 ModelCreating 方法中应用该参数:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Book>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedOnAdd();
});
}
否则,您应该在将书籍实体添加到 DB 之前为 Id 分配适当的值。
推荐阅读
- clonezilla - 如何更改 Clonezilla 默认菜单选择项
- javascript - 为什么javascript`for`循环快速静音/取消静音视频
- php - Laravel 试图检索模型的 ID 但不工作?
- sql - 使用联合将不同的查询与不同的组连接起来
- javascript - 如何将使用在根组件中声明的 setState 的对象排序到不同的文件中?
- c# - 在控制器中添加后模型视图模型字典值 null
- c# - 与 C# 中的 Paint 方法相比,使用 OnPaint 覆盖方法有什么优势?
- javascript - 当我需要同时过滤多个东西时,如何调用过滤器一次?
- android - 如何为 android 应用付费和免费版本处理两种不同的功能
- c - 如何创建一个将输入除以 2 的收缩函数?