Nicolas Restrepo Nicolas Restrepo - 1 year ago 81
ASP.NET (C#) Question

It's 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?

Answer Source

No, there isn't. But you can always built 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download