I have an wpf app + EF Core 2 to access Data (several tables in db)
The software is plan to be in 2 or 3 differents "versions" (depending on the business, but will share the same db and the "same ui" with various views).
Today the DbContext contains lots of tables (to cover all the versions) and i want to separate this one in smalls many Dbcontext(s)
So What is the best approach ?
I would have DI /IOC to resolve a CurrentContext (return DBVersion1 or DBVersion2 or DBVersion3 according to the type of version (set by the user when launching UI)
Is the code below is the good approach ?
public class DBVersion1 : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DBSet<User>{ get; set; }
public DBSet<Books> { get; set; }
public DBSet<Engine> { get; set; }
}
public class DBVersion2 : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DBSet<User>{ get; set; }
public DBSet<Books> { get; set; }
public DBSet<Engine> { get; set; }
public DBSet<Paiement>{ get; set; }
public DBSet<Invoice> { get; set; }
}
public class DBVersion3 : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public static DbContext CurrentContext
{
get
{
var _servicesCollection = new ServiceCollection().
AddDbContext<DBVersion1 >(options => options.UseSqlServer(@"Server=
(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"))
.AddDbContext<DBVersion2 >(options => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"))
.AddDbContext<DBVersion3>(options => options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"))
.BuildServiceProvider();
return _mainContext ?? (_mainContext = _servicesCollection.GetService<DBVersion1>());
}
}
- How can i switch between
Dbcontext1/2/3inCurrentContextgetter? - Refactoring the actual may be difficult ? ie today the viewmodel's can have
var v = DBContext.Paiement....et
after :
var v = CurrentContext.Paiement ? => does not compile in the case of Version1 ? (or maybe it's no sens in this case ?)
Thanks
DbContextis the equivalent of database. If you have single database, then you should have single context. Anything else will just cause you a problems in one or another way.