Let's say, in theory, I have a database with an unknown number of tables, named like:
MyTable1
MyTable2
MyTable3
..
and so on. Each of these tables has the exact same schema. I will not know how many of these tables exist in the database.
Using EF5.0 and code-first, I want to be able to reference any one of these tables through one DbContext by passing in a parameter:
using (var db = new MyContext())
{
db.GetMyTable(2).ForEach(e => Console.WriteLine("Table 2 entry: " + e.MyField));
db.GetMyTable(5).ForEach(e => Console.WriteLine("Table 5 entry: " + e.MyField));
}
Is this possible?
Another way I thought of doing this would be to create completely different contexts and supply the correct .ToTable() in the mapping:
public class MyContext : DbContext
{
private int _tableNumber;
static MyContext()
{
Database.SetInitializer<MyContext>(null);
}
public MyContext(int tableNumber) : base("Name=TheContextName")
{
_tableNumber = tableNumber;
}
public DbSet<MyTable> MyTableEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
System.Data.Entity.ModelConfiguration.Conventions.
modelBuilder.Configurations.Add(new MyTableMap(_tableNumber));
}
}
public class MyTableMap : EntityTypeConfiguration<MyTable>
{
public MyTableMap(int tableNumber)
{
// Primary Key
this.HasKey(t => t.id);
// Table & Column Mappings
this.ToTable("MyTable" + tableNumber);
this.Property(t => t.id).HasColumnName("id");
this.Property(t => t.n).HasColumnName("MyField");
}
}
And then I could just operate with a separate context based on the table I wanted to deal with:
Console.WriteLine("Contents of MyTable1:");
using (var db = new MyContext(1))
{
db.MyTableEntries.ToList().ForEach(n => Console.WriteLine(n.MyField));
}
Console.WriteLine("Contents of MyTable2:");
using (var db = new MyContext(2))
{
db.MyTableEntries.ToList().ForEach(n => Console.WriteLine(n.MyField));
}
However, what happens is that OnModelCreating() in the context only gets called once on the first instantiation, so that table is always mapped to MyTable1. Is there some kind of caching that can be turned off so that OnModelCreating() gets called every time, and if so, is this a good idea? Is there a more elegant way of doing this?