DEV Community

jsakamoto
jsakamoto

Posted on

3 2

How to get a DbContext from a DbSet in EntityFramework Core 2.0.

In EntityFramework Core programming, You can get a DbContext object from a DbSet object like this:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;

public static class DbContextGetter
{
  public static DbContext GetDbContext<T>(this DbSet<T> dbSet) where T: class
  {
    var infrastructure = dbSet as IInfrastructure<IServiceProvider>;
    var serviceProvider = infrastructure.Instance;
    var currentDbContext = serviceProvider.GetService(typeof(ICurrentDbContext))
                               as ICurrentDbContext;
    return currentDbContext.Context;
  }
}

// How to use:
// 
// class MyDbContext {
//    public DbSet<FooBar> FooBar { get; set; }
// }
// ...
// var myContext = new MyDbContext();
// var contextFromDbSet = myContext.FooBar.GetDbContext();
//                                         ~~~~~~~~~~~~~~
// myContext == contextFromDbSet; // -> true

Enter fullscreen mode Exit fullscreen mode

Happy coding :)

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay