Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a DbContext Interface or abstract class and use it to inject different DbContext Objects?

I have a software product which database was created on SQLServer and the table and column names were defined by the dev team, the model was then imported to Visual Studio using Database First approach , now we are developing the same type of solution for other company that uses ORACLE and request a naming convention for the Tables and Columns so in order to not change the existing code and use Code-First Approach, I created a DbContext with the correct naming conventions using the [Column] attribute for all the classes properties, but now I'm trying to create an interface so we can Inject different DbContext and in the future we have a more flexible solution.

I'm new to .Net but my approach is to make an Abstract Class for the DbContext, and an interface for every class that represents a table so in the implementation of each of those classes i can change the table and columns names if necessary. My question is, it's possible? and is a good approach?

like image 370
Nicolas Restrepo Avatar asked Jun 14 '16 16:06

Nicolas Restrepo


People also ask

Which method is used to add a DbContext to an application?

The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder . Learn how to configure a DbContext class at here.

What is the purpose of a DbContext class?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

Which of the below method is used for adding DbContext class as service?

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.

Should you use using with DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.


1 Answers

No, there isn't. But you can always build one like this:

interface IDbContext : IDisposable
{
    DbSet<TEntity> Set<TEntity>() where TEntity : class;

    Task<int> SaveChangesAsync();
}

public class MyDbContext : DbContext, IDbContext
{
    public MyDbContext()
        : base("myConnectionString")
    { }

    //implementation
}

And inject IDbContext when needed.

like image 53
Cheng Chen Avatar answered Oct 21 '22 18:10

Cheng Chen