entity-framework - EF core 3 之后 IDENTITY 列的变化

标签 entity-framework asp.net-core entity-framework-core

直到 .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).CurrentValue will return the temporary value even though blog.Id itself hasn't been set.

选项 #1 没有意义(显然受影响的地方已经使用商店生成的 key )。

如果您有导航属性,则选项 #2 更可取。

选项 #3 更接近于先前的行为,但需要访问数据库上下文。

关于entity-framework - EF core 3 之后 IDENTITY 列的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147041/

相关文章:

c# - 没有 setter 的 Entity Framework 核心属性

sql-server - Entity Framework 6.2数据库第一次预热

validation - 从 asp-validation-summary 获取所有非模型错误

c# - ASP.NET Core - 处理 404 和 500 错误

c# - 更新大量数据时重复键值错误

c# - 初始数据库迁移 : No database provider has been configured for this DbContext

sql - 什么时候创建新表?

c# - 将 Insert into Select 翻译成 Entity Framework

c# - 将 .net 4.0 中的 Entity Framework 与 Oracle 数据库一起使用 - 可能吗?

c# - 如何使用 asp.net core 2 测试具有属性的方法?