EF Core Add function returns negative identifier

Today I noticed a strange thing when I tried to save the entity and return its identifier to EF Core.

Before: The Id is 0 before it was added to databaseAfter:Now the id has been changed to a negative value

I was thinking about whether this was before calling saveChanges (), but it works with another object with a similar setting.

PS: I use a unit of work to save all changes at the end.

What was the reason?

+6
source share
2 answers

It will be negative until you save the changes. Just call Savethe context.

_dbContext.Locations.Add(location);
_dbContext.Save();

, . , .

IDENTITY , . , , - .

+9

, , : https://github.com/aspnet/EntityFrameworkCore/issues/6147

:

 public class IntValueGenerator : TemporaryNumberValueGenerator<int>
 {
     private int _current = 0;

     public override int Next(EntityEntry entry)
     {
         return Interlocked.Increment(ref _current);
     }    
 }

:

public class CustomContext: DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var type in modelBuilder.Model.GetEntityTypes().Select(c => c.ClrType))
        {
            modelBuilder.Entity(type, b =>
            {              
                b.Property("Id").HasValueGenerator<IntValueGenerator>();
            });
        }
        base.OnModelCreating(modelBuilder);
    }
}

"1", .

0

Source: https://habr.com/ru/post/1667210/


All Articles