问题描述
直到.donet core 2.2中使用的EF核心版本,在.Add
命令之后,EF用一个大的负数填充key列.
Until EF core version used in .donet core 2.2, after the .Add
command, EF fills the key column with a big negative number.
升级 3.0 后不再发生这种情况.
After 3.0 upgrade this does not happens anymore.
代码如下:
var appointment = new Appointment
{
Date = DateTime.Today,
ProfessionalId = schedule.ProfessionalId
};
await service.AddAsync(appointment);
string message = null;
if (service.AddLastPrescription(appointment.Id, schedule.PacienteId))
....
问题是现在appointment.Id"为零,调用服务函数会失败(FK错误).
The problem is that now the "appointment.Id" is zero and the call to the service function will fail (FK error).
这种行为是 3.0 中的预期吗?
This behavior was expected in 3.0?
AddAsync 函数
AddAsync function
private DbSet<T> dbSet;
public async Task AddAsync(T t)
{
await dbSet.AddAsync(t);
}
其中 T 是 ModelBase:
where T is ModelBase:
public class ModelBase
{
[Key]
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
推荐答案
是的,它是 3.0 重大更改 - 临时键值不再设置到实体实例.
建议的解决方案有:
- 不使用商店生成的密钥.
- 设置导航属性以形成关系而不是设置外键值.
- 从实体的跟踪信息中获取实际的临时键值.例如,
context.Entry(blog).Property(e => e.Id).CurrentValu
e 将返回临时值,即使blog.Id
本身没有t 已设置.
选项 #1 没有意义(显然受影响的地方已经使用存储生成的密钥).
Option #1 doesn't make sense (apparently the affected places already use store generated keys).
如果您有导航属性,则选项 2 更可取.
Option #2 is preferable if you have navigation properties.
选项#3 更接近于之前的行为,但需要访问数据库上下文.
Option #3 is closer to the previous behavior, but requires access to the db context.
这篇关于EF core 3 之后 IDENTITY 列的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!