My database has different schemes depending on the user's choice at runtime.
My code is below:
public partial class FashionContext : DbContext { private string _schema; public FashionContext(string schema) : base() { _schema = schema; } public virtual DbSet<Style> Styles { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlServer(@"Server=.\sqlexpress;Database=inforfashionplm;Trusted_Connection=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Style>() .ToTable("Style", schema: _schema); } }
After testing. I created a context instance using "schema1". So far, so good.
But when I create another instance of the context with another schema "schema2", the resulting data in which the schema is still in "schema1".
Here is the implementation:
using (var db = new FashionContext("schema1")) { foreach (var style in db.Styles) { Console.WriteLine(style.Name); } } Console.ReadLine(); Console.Clear(); using (var db = new FashionContext("schema2")) { foreach (var style in db.Styles) { Console.WriteLine(style.Name); } } Console.ReadLine();
Later, I noticed that OnModelCreating is called only once, so it is never called again when you create a new instance of the context of the same connection string.
Is it possible to have a dynamic circuit at runtime? Note: this is possible in EF6
entity-framework
Petrick lim
source share