Skip to content

Getting the Id for the next insert #27387

@umamaheswareada550

Description

@umamaheswareada550

Hi Team, we are trying to upgrade EFCore2.1 to 5.0 and faced this issue. Temporary values are not generated by EFCore 5 thereby unable to insert record due to FK exception. y.Id has zero value after adding it to context

Consider the following example

Below works on EFCore2.2

var x = new MyEntity();        // x.Id = 0
dbContext.Add(x);              // x.Id = -2147482624 <-- EF Core generated id
dbContext.SaveChangesAsync(); 

var y = new MyOtherEntity();   // y.Id = 0
dbContext.Add(y);              // y.Id = -2147482623 <-- EF Core generated id
x.MyEntityId = y.Id;           // y.MyEntityId = -2147482623 <-- EF Core generated id
dbContext.SaveChangesAsync();

Debug.WriteLine(x.Id);         // 1261 <- EF Core replaced temp id with "real" id
Debug.WriteLine(y.MyEntityId); // 1261 <- reference also adjusted by EF Core

Below doesn't work on EFCore5.0

var x = new MyEntity();        // x.Id = 0
dbContext.Add(x);              // x.Id = -0 <-- EF Core generated id
dbContext.SaveChangesAsync(); 

Debug.WriteLine(x.Id);         // 1261 <- EF Core replaced temp id with "real" id

var y = new MyOtherEntity();   // y.Id = 0
dbContext.Add(y);              // y.Id = 0 <-- EF Core generated id
x.MyEntityId = y.Id;           // x.MyEntityId = 0 <-- EF Core generated id
dbContext.SaveChangesAsync(); <-- throws FK SqlClient exception

Can you please guide me if i am missing anything?

Include provider and version information

EF Core version: 5.0.13
Database provider: (Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (.NET 6.0)
Operating system: Windows10
IDE: (Visual Studio 2022 17.0)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions