实体类型 'Library' 上的 属性 'BookId' 具有临时值。显式设置永久值或确保数据库是
The property 'BookId' on entity type 'Library' has a temporary value. Either set a permanent value explicitly or ensure that the database is
当我使用 Entity Framework 核心和种子数据进行迁移时,出现此错误:
The property 'BookId' on entity type 'Library' has a temporary
value. Either set a permanent value explicitly or ensure that the
database is configured to generate values for this property.
如果您与 ForeignKey 有依赖关系,该消息意味着您为您的密钥提供了一个不存在的值。
当我有唯一索引时,我遇到了同样的异常,AddRange 在唯一索引上失败,然后在 catch 异常块中尝试删除整个插入的集合。
(不是我的代码,但我必须修复它 :-))
代码示例(简化):
try {
context.AddRange(users); // List<User>, has property List<Contact>
context.SaveChanges(); // throws exception on unique index
} catch (Exception ex) {
context.RemoveRange(users); // this throws exception "The property 'UserID' on entity type 'Contact' has a temporary value"
throw;
}
错误信息可能会误导和造成混淆,起初我以为是数据库设置问题。
我在(错误地)将同一对象两次添加到列表中、使用 added/modified 值更新上下文范围并保存回数据库时遇到此错误:
例如:
list = _context.SomeList.ToList();
var obj = new Obj();
list.Add(obj);
.......
list.Add(obj); //<- second add of the same object
.......
_context.UpdateRange(list);
_context.SaveChanges(); //<- error
当我使用 Entity Framework 核心和种子数据进行迁移时,出现此错误:
The property 'BookId' on entity type 'Library' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.
如果您与 ForeignKey 有依赖关系,该消息意味着您为您的密钥提供了一个不存在的值。
当我有唯一索引时,我遇到了同样的异常,AddRange 在唯一索引上失败,然后在 catch 异常块中尝试删除整个插入的集合。 (不是我的代码,但我必须修复它 :-))
代码示例(简化):
try {
context.AddRange(users); // List<User>, has property List<Contact>
context.SaveChanges(); // throws exception on unique index
} catch (Exception ex) {
context.RemoveRange(users); // this throws exception "The property 'UserID' on entity type 'Contact' has a temporary value"
throw;
}
错误信息可能会误导和造成混淆,起初我以为是数据库设置问题。
我在(错误地)将同一对象两次添加到列表中、使用 added/modified 值更新上下文范围并保存回数据库时遇到此错误:
例如:
list = _context.SomeList.ToList();
var obj = new Obj();
list.Add(obj);
.......
list.Add(obj); //<- second add of the same object
.......
_context.UpdateRange(list);
_context.SaveChanges(); //<- error