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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay