I am using EF Core to insert entries and I noticed that when I debug this line of code context.MyEntityDbSet.AddRangeAsync(records)
it takes a second to load as opposed to context.MyEntityDbset.AddRange(records)
it happens instantly. Is there a DB call happening when calling the AddRangeAsync
method? Is it any different than the AddRange
one?
AddRangeAsync(Object[]) Begins tracking the given entity, and any other reachable entities that are not already being tracked, in the Added state such that they will be inserted into the database when SaveChanges() is called.
AddRange() method attaches a collection of entities to the context with Added state, which will execute the INSERT command in the database for all entities on SaveChanges() . In the same way, the DbSet.
RemoveRange(IEnumerable<Object>) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called. RemoveRange(Object[]) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.
Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.
According to the official EF Core docs AddRangeAsync(IEnumerable<TEntity>, CancellationToken)
is supposed to be used with special value generators like such requiring a database round trip. For example if you use SqlServerValueGenerationStrategy.SequenceHiLo
to allocate blocks of IDs in advance, when a new entity is tracked by EF it might need first to query the database and ask for a new "Hi" (more about the Hi/Lo algorithm can be found here What's the Hi/Lo algorithm?). So when the idea is to just set the entity to Added
state and SqlServerValueGenerationStrategy.SequenceHiLo
is not required, AddRange
is used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With