Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between AddRange and AddRangeAsync in EF Core

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?

like image 555
Angel Venchev Avatar asked May 21 '19 15:05

Angel Venchev


People also ask

What is AddRangeAsync?

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.

How do I use AddRange in Entity Framework?

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.

What is RemoveRange in Entity Framework?

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.

Should I use EF6 or EF core?

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.


1 Answers

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.

like image 162
Panayot Todorov Avatar answered Sep 28 '22 16:09

Panayot Todorov