3

Until EF core version used in .donet core 2.2, after the .Add command, EF fills the key column with a big negative number.

After 3.0 upgrade this does not happens anymore.

Here is the code:

var appointment = new Appointment
{
    Date = DateTime.Today,
    ProfessionalId = schedule.ProfessionalId
};
await service.AddAsync(appointment);

string message = null;
if (service.AddLastPrescription(appointment.Id, schedule.PacienteId))
 ....

The problem is that now the "appointment.Id" is zero and the call to the service function will fail (FK error).

This behavior was expected in 3.0?

update

AddAsync function

private DbSet<T> dbSet;

public async Task AddAsync(T t)
{
    await dbSet.AddAsync(t);
}

where T is ModelBase:

public class ModelBase
{

    [Key]
    public int Id { get; set; }

    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }

}
0

1 Answer 1

6

This behavior was expected in 3.0?

Yes, it is one of the 3.0 Breaking Changes - Temporary key values are no longer set onto entity instances.

The proposed solutions there are:

  • 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.

Option #1 doesn't make sense (apparently the affected places already use store generated keys).

Option #2 is preferable if you have navigation properties.

Option #3 is closer to the previous behavior, but requires access to the db context.

2
  • Not sure how exactly context.Entry(blog).Property(e => e.Id).CurrentValue works? will it give the actual primary key value from database? If it is then what will happen if multiple insertion happen at the same time? Sep 28, 2019 at 17:38
  • 1
    @Tanvir It works the same way PK property of the object (blog.Id) worked in 2.x, i.e. initially will have temporary generated value.
    – Ivan Stoev
    Sep 28, 2019 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.