Sigit Budi
Sigit Budi

Reputation: 51

Using Entity Framework for 2 databases in .NET

I have no idea how to use EF to connect to 2 databases separately, I just use 1 database only before.

I have to model ActivityLog and RegistrationData.

Here are the connection strings:

<connectionStrings>
    <add name="DevSaveLog" 
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=BIFASTAPI_Log;Integrated Security=True" 
         providerName="System.Data.SqlClient" />
    <add name="DevSaveRegis" 
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=BIFASTAPI_Reg;Integrated Security=True" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

This is my existing DContext (using an old connection string)

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() : base("DefaultConnection")
    {
    }

    public DbSet<ActivityLog> ActivityLogs { get; set; } //<<< I want this in DevSaveLog
    public DbSet<RegistrationData> RegistrationDatas { get; set; } //<< I want this in DevSaveRegis
}

How can I apply those? Thanks sorry for my bad English :)

Upvotes: 0

Views: 425

Answers (1)

themassiveone
themassiveone

Reputation: 71

As Ben already pointed out in the comments, you will need two seperate DbContext Classes. Each will use its own connection string in order to connect to its specific database. You might inject your specific connection string using Dependency Injection.

public class LogContext : DbContext
{
    private IConfiguration config { get; set; }
    public DbSet<ActivityLog> ActivityLogs { get; set; }

    public LogContext(IConfiguration config)
    {
        this.config = config;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // use configuration string called "DevSaveLog"
    }
}

public class RegistrationContext : DbContext
{
    private IConfiguration config { get; set; }
    public DbSet<RegistrationData> RegistrationDatas { get; set; }

    public RegistrationContext(IConfiguration config)
    {
        this.config = config;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        // use configuration string called "DevSaveRegis"
    }
}

You then want to inject both of these Context into the class, you want to use them with.

Example:

public class Example
{
    private LogContext logContext {get;set;}
    private RegistrationContext registrationContext {get;set;}
    public Example(LogContext log, RegistrationContext registration)
    {
        this.logContext = log;
        this.registrationContext = registration;
    }

    public void ExampleMethod()
    {
        var logs = logContext.ActivitryLogs;
        var registrations = registrationContext.RegistrationDatas;
    }
}

Upvotes: 1

Related Questions