It's possible to create a DbContext Interface or abstract class and use it to inject different DbContext Objects? c# entity-framework


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?

4/19/2019 2:16:15 PM

Accepted Answer

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")
    { }


And inject IDbContext when needed.

7/4/2018 3:42:52 PM

Popular Answer

You can use a generic class with several type parameter constraints and, for example, a public property of the constrained type to inject your DbContext:

class Stuff<T> where T : DbContext, IMyContext
    public T Context { get; set; }
    // other members

This makes you able to use DbContext as well as IMyContext functionality for variables of type T.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow