简体   繁体   中英

Multiple instances of same DBContext

Good morning,

I have been working in one project of my own and I would know if someone knows if I can have multiple instances of the same DBContext in my application.

I would have 2 instances of databases that are connected in Startup.cs like this:

services.AddDbContext<MyApplicationDBContext>(options => options.UseSqlServer(_config.GetConnectionString("StringConnection1")));
services.AddDbContext<MyApplicationDBContext>(options => options.UseSqlServer(_config.GetConnectionString("StringConnection2")));

services.AddScoped<IAppRepository, AppRepository>();

This is how I build MyApplicationDbContext :

public partial class MyApplicationDBContext : IdentityDbContext<AppUsers>
{
    public virtual DbSet<Book> Books{ get; set; }
    public virtual DbSet<Film> Films{ get; set; }

    public MyApplicationDBContext(DbContextOptions<MyApplicationDBContext> options) : base(options)
    {

    }
}

And at last, I would like to have on my repository something like this:

public class AppRepository: IAppRepository
{
    private IConfigurationRoot _config;
    private MyApplicationDBContext _cntx;
    private MyApplicationDBContext _cntx2;
    private UserManager<AppUsers> _userManager;

    public AppRepository(MyApplicationDbContext cntx, MyApplicationDbContext cntx2, IConfigurationRoot config, UserManager<AppUsers> userManager)
    {
        _cntx = cntx;
        _cntx2 = cntx2;
        _config = config;
        _userManager = userManager;
    }

    public async Task<IEnumerable<Book>> GetBookByDatabase(string book, int database)
    {
        if(database == 1)
           return _cntx.GetBook(book);
        if(database == 2)
           return _cntx2.GetBook(book);
        else
           return null;
    }
}

The main purpose of this code it's to have one instance of the application that could insert and query data from 2 different databases.

This one is the first post I've ever made, I'm sorry if I wrote something wrong.

Appreciate your answers.

Well, if your goal is to have two databases then all you have to do is specify different database names in the two connection strings.

However, if the point is to separate the data by user, then I would say you are far better off just storing the user name in a key field in the tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM