DEV Community

jsakamoto
jsakamoto

Posted on

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 :)

Top comments (0)