rezanouri
rezanouri

Reputation: 137

I Want Using two DbContext asp.net core

I want using two datacontext for myapp

 services.AddDbContext<AuthenticationContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

                services.AddDbContext<DataContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MyConection"))
                );

The DbContextOptions passed to the AuthenticationContext constructor must be a DbContextOptions. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions parameter rather than a non-generic DbContextOptions parameter.'

Upvotes: 3

Views: 4178

Answers (2)

David Graham
David Graham

Reputation: 468

Register your other contexts before the ApplicationDbContext / Identity in Startup.cs.

services.AddDbContext<MyDbContext>
services.AddDbContext<ApplicationDbContext>

Upvotes: 2

Ryan
Ryan

Reputation: 20126

You could use multiple dbcontext in your app, adding new dbcotext is the same to your first dbcontext.

1.Create a dbContext

public class DataContext: DbContext
{
    public DataContext(DbContextOptions<DataContext> options)
        : base(options)
    {
    }
}

2.appsettings.json:

"ConnectionStrings": {
    "IdentityConnection": "xxx",
    "MyConection": "xxx"
},

3.Register the dbcontext

 services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyConection"))
            );

If you would like to add migration,just specify which context you would like to use, for example:

Add-Migration init -Context DataContext
Update-Database -Context DataContext

Upvotes: 5

Related Questions