Yes,you can do that.
You can do that using Finding the Classes :
[AttributeUsage(AttributeTargets.Class)]
public class PersistentAttribute : Attribute
{
}
Now you can add some logic to the OnModelCreating
method of your context
to scan assemblies and add any classes with the [Persist]
attribute as shown below.
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var entityTypes = assembly
.GetTypes()
.Where(t =>
t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true)
.Any());
foreach (var type in entityTypes)
{
entityMethod.MakeGenericMethod(type)
.Invoke(modelBuilder, new object[] { });
}
}
}
}
You can use below mentioned code based data migration method hence automatically change the database when new classes or properties are added to the model.
var config = new DbMigrationsConfiguration<MyContext> { AutomaticMigrationsEnabled = true };
var migrator = new DbMigrator(config);
migrator.Update();
You can read more about this : Dynamically Building A Model With Code First
Update : How to Query a Dynamic Table ?
public IEnumerable<ResultTableTemplate> GetResultsFromTable(string tableName) {
using (var context = new MyContext()) {
var query = context.ExecuteStoreQuery<ResultTableTemplate>("SELECT " +
"ALL_THOSE_COLUMN_NAMES... " +
"FROM " + tableName;
return query.ToList();
}
}
See this for more : Querying data using Entity Framework from dynamically created table
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…