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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more