问题
I noticed a weird thing today when I tried to save an entity and return its id in EF Core
Before: After:
I was thinking about if it was before calling saveChanges() but it works with another entity with a similar setup.
ps: I use unit of work to save all changes at the end.
What was the reason?
回答1:
It will be negative until you save your changes. Just call Save
on the context.
_dbContext.Locations.Add(location);
_dbContext.Save();
After the save, you will have the ID which is in the database. You can use transactions, which you can roll back in case there's a problem after you get the ID.
The other way would be not to use the database's built-in IDENTITY fields, but rather implement them yourself. This can be very useful when you have a lot of bulk insert operations, but it comes with a price — it's not easy to implement.
回答2:
Apparently, this isn't a bug it's a feature: https://github.com/aspnet/EntityFrameworkCore/issues/6147
It's not too arduous to override this behavior like so:
public class IntValueGenerator : TemporaryNumberValueGenerator<int>
{
private int _current = 0;
public override int Next(EntityEntry entry)
{
return Interlocked.Increment(ref _current);
}
}
Then reference the custom value generator here:
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);
}
}
This will result in temporary Id's that increment from "1", however, more effort is required to prevent key conflicts when attempting to save.
来源:https://stackoverflow.com/questions/41732585/ef-core-add-function-returns-negative-id