tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Useful methods on Entity Framework Core’s DbContext

12 Jul 2017 Entity Framework, Entity Framework Core

I completely missed some handy methods on Entity Framework Core’s DbContext. Maybe you did too. And that would be a pity.

The methods I’m talking about are known to you for sure. These methods were originally available (and still are) on DbSet<T> - Add, Remove, AddRange, RemoveRange. The problem with having these on DbSet<T> is that you have to know the type (or the DbSet<T> property) to call these. Doable, but clearly not a smooth sailing. Instead of using reflection you might end up using change tracker directly, where most of the methods take or return plain object values.

On Entity Framework Core the path is super easy. These methods are available directly on DbContext. For example Add(object) and Add<TEntity>(TEntity). What’s more, as I mentioned, these methods are virtual and thus you can override these and put a custom logic there, if you need to (don’t forget this isn’t the only way to i.e. add object to the change tracker).

Looks like somebody was thinking about this. Thumbs up.