Are there disadvantages bypassing DBSet when calling Find,Add,Update etc. on the context?

103 Views Asked by At

Are there disadvantages bypassing DBSet when calling Find,Add,Update etc. on the context?

creating or getting the DBSet should cost some time. And as far as I know, the Add, Update, Remove methods only set the entity's EntityState to Added,Modified,Deleted and do nothing else. The real action will be performend when calling SaveChanges(Async). So the question remains: Is it good to omit the DbSet if possible? see first examples.

calling

dbContext.Find(typeof(TEntity), id);
dbContext.Add(entity);
dbContext.Update(entity);
dbContext.Remove(entity);
...

instead of

dbContext.Set<TEntity>.Find(id);
dbContext.Set<TEntity>.Add(entity);
dbContext.Set<TEntity>.Update(entity);
dbContext.Set<TEntity>.Remove(entity);
1

There are 1 best solutions below

0
Dennis On

Subsequent calls of Set<TEntity> method are cheap because of results caching. The first call also not so expensive comparing to whole EF overhead.

Set<TEntity> returns InternalDbSet<TEntity>, whose Add, Update, etc just redirect calls to set's context.

As a result, there's no any significant differece.

For reference, see:
https://github.com/dotnet/efcore/blob/master/src/EFCore/DbContext.cs https://github.com/dotnet/efcore/blob/master/src/EFCore/Internal/InternalDbSet.cs