DEV Community

EF Core multiple Database providers

Mohsen Esmailpour on May 11, 2021

Most of the time you don't need to have multiple database providers, for example, you start with the SQL Server provider and there is no need to sw...
Collapse
 
lmcgs profile image
Can Ürek

I couldn't use this approach with the IdentityDbContext. TContextService and TContextImplementation logic don't work as expected. And I got an error like this;

"An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Some services are not able to be constructed (Error while validating the service descriptor..."

Do you have any idea to fix this situation?

Collapse
 
moesmp profile image
Mohsen Esmailpour • Edited

I upgraded the sample project in GitHub to .NET 7.0 and it's working fine. Please follow the sample project or share your codes by a git repo.

Collapse
 
lmcgs profile image
Can Ürek

Thanks for the reply. I handled it somehow. I'll also look at your repo.

Collapse
 
nomada2 profile image
nomada2

can you add nosql database like azure cosmos documentdb?

Collapse
 
moesmp profile image
Mohsen Esmailpour

Sure, it's just like PostgresSQL but it does not need to generate migration at all, and by calling context.Database.EnsureCreated() database will be created. Check out the sample project on github.

Collapse
 
nomada2 profile image
nomada2

thanks, i'll check

Collapse
 
magals profile image
magals

Is there a way to get rid of options.UseSqlServer(Configuration.GetConnectionString("MsSqlConnection")); to MsSqlDbContext and pass the connection string when services.AddDbContext(); ?

I ask because if the work with DbContext is transferred to a separate project as a library, then it will not be correct for this library to have a strictly fixed entry to the path to the Database. (Configuration.GetConnectionString("MsSqlConnection"))

Collapse
 
moesmp profile image
Mohsen Esmailpour

@magals you can inject a model that has a connection string property instead of IConfiguration to DbContext and get ride of hardcoded key name.

public class SqlServerDbContext(ConnectionStringModel model)
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
       options.UseSqlServer(_model.ConnectionString);
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mblataric profile image
Mario Blatarić

Do not use modelBuilder.ApplyConfigurationsFromAssembly() method to load configuration.

Could you please comment why not?

Collapse
 
moesmp profile image
Mohsen Esmailpour

Because ApplyConfigurationsFromAssembly scans the assembly and loads all configuration but only provider-specific configuration should be added.

Collapse
 
minh_nguynng_be868cea profile image
Minh Nguyễn Đăng

you can use filter

Collapse
 
hussein_nm profile image
Hussein NM

Thanks