A.HADDAD
A.HADDAD

Reputation: 1906

Multiple Databases with Same schema EF Core?

I have a project where I need to use two different databases of the same SQL server connection.

For the first database, I used the DatabaseFirstApproach which is common for all users.

The second database is specific for each user, but it is identic in its schema, there are many databases in SQL server.

My question is, how to add these databases in my project?

They have the same schema, so they should have the same model, can we create a shared model for differents databases with ef core?

                   Model
 db1 db2 db3 db4 db5 db6 db7 db8 db9 db10

Should I add them all with the database first approach?

That would make the project structure repetitive (the same models would be repeated many times)!

For each client in my application, I would use this code :

 //Connect with the selected customer's connection string
          using (SqlConnection ccn = new SqlConnection(EConnectionString.ToString()))
        {
            DateTime lastDayinTheYear = new DateTime(DateTime.Now.Year, 12, 31);
            GetListEntrepriseActivitesByPeriode(ccn,IdEnterprise, DateTime.Now, lastDayinTheYear);

        };

update

this is my " OnConfiguring" method :

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {

            optionsBuilder.UseSqlServer("Server=.;Database=AZPDBDEMOGZ;UID=DEVAZPROJET-2019;PWD=****");
        }
    }

Upvotes: 1

Views: 908

Answers (1)

Roma Ruzich
Roma Ruzich

Reputation: 752

As I wrote in comments:

Domain model is same for each of database (it is not needed to start database first generator for each database, it is enough to use it for one database).You can connect to each database using one connection. But in connection you should change database name to name you need.

If you don't join data from different databases you don't need different context. If you need cross database queries then you need different dbcontexts.

You should correct your dbContext class:

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

    public DbSet<Blog> Blogs { get; set; }

    //without OnConfiguring method
}

Then you can use this dbContext as:

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer("You connection string");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}

More details you can find here

Upvotes: 2

Related Questions