直到 .donet core 2.2 中使用的 EF core 版本,在 .Add
命令之后,EF 用一个大的负数填充键列。
3.0 升级后,这种情况不再发生。
代码如下:
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 错误)。
这种行为在 3.0 中是预期的?
更新
添加异步函数
private DbSet<T> dbSet;
public async Task AddAsync(T t)
{
await dbSet.AddAsync(t);
}
其中 T 是模型库:
public class ModelBase
{
[Key]
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
最佳答案
This behavior was expected in 3.0?
是的,它是 3.0 Breaking Changes 之一- Temporary key values are no longer set onto entity instances .
建议的解决方案有:
- Not using store-generated keys.
- Setting navigation properties to form relationships instead of setting foreign key values.
- Obtain the actual temporary key values from the entity's tracking information. For example,
context.Entry(blog).Property(e => e.Id).CurrentValu
e will return the temporary value even thoughblog.Id
itself hasn't been set.
选项 #1 没有意义(显然受影响的地方已经使用商店生成的 key )。
如果您有导航属性,则选项 #2 更可取。
选项 #3 更接近于先前的行为,但需要访问数据库上下文。
关于entity-framework - EF core 3 之后 IDENTITY 列的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147041/