How to get to entities using base DbContext class in EF Core?

.net-core c# entity-framework-core

Question

My project contains two different databases, which I needed to scaffold at the beginning (database-first approach). I would like to follow the repository pattern, but my repositories need to use different DbContext's. I wanted to create a BaseRepository class which has a 'polymorphic' DbContext property, as shown below on the attached snippet:

    internal abstract class BaseRepository
    {
        public BaseRepository(DbContext dbContext)
        {
            DbContext = dbContext;
        }

        protected DbContext DbContext { get; private set; }

        public async Task<int> SaveChangesAsync() =>
            await DbContext.SaveChangesAsync();
    }

And exemplary child class:

internal class GameRepository : BaseRepository, IGameRepository
    {
        public GameRepository(SomeDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<GameEntity> GetGamesAsync() =>
            await DbContext... ???????
    }

The problem is that the database context in the derived class has type DbContext, so I cannot access my entities. Is there any way to access entities stored in the derived SomeDbContext class, but using the base class? If not, what is the best solution for such a problem?

1
2
4/17/2020 10:10:28 AM

Accepted Answer

Is there any way to access entities stored in derived SomeDbContext class, but using the base class?

Yes. You can by using the Set<T> generic method of your base class DbContext like below:

public async Task<GameEntity> GetGamesAsync() =>
    await DbContext.Set<GameEntity>().ToListAsync();
1
4/17/2020 10:03:04 AM

Popular Answer

Since you know the type of DbContext (it can only be SomeDbContext in the given class), you can safely cast it:

public async Task<GameEntity> GetGamesAsync() =>
    await ((SomeDbContext)DbContext).Games...


Related Questions





Related

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