Bulchsu
Bulchsu

Reputation: 690

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

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?

Upvotes: 2

Views: 422

Answers (2)

CodeNotFound
CodeNotFound

Reputation: 23190

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();

Upvotes: 1

janw
janw

Reputation: 9606

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...

Upvotes: 0

Related Questions