EF core 3 之后 IDENTITY 列的变化 [英] Changes in IDENTITY column after EF core 3

查看:26
本文介绍了EF core 3 之后 IDENTITY 列的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到.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 中的预期吗?

This behavior was expected in 3.0?

是的,它是 3.0 重大更改 - 临时键值不再设置到实体实例.

建议的解决方案有:

  • 不使用商店生成的密钥.
  • 设置导航属性以形成关系而不是设置外键值.
  • 从实体的跟踪信息中获取实际的临时键值.例如,context.Entry(blog).Property(e => e.Id).CurrentValue 将返回临时值,即使 blog.Id 本身没有t 已设置.
  • 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).CurrentValue will return the temporary value even though blog.Id itself hasn't been set.

选项 #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 列的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆