问题描述
是否可以使用 EF 代码优先在运行时创建表?我可以使用 C# CodeDOM(reflection) 在运行时创建我的模型类,但我无法在运行时设置我的 Dbcontext 类的 dbSet 属性.你的想法是什么?在运行时动态创建表的最佳解决方案是什么?...有些人对我说,唯一的方法是使用经典的 ADO.Net.
Is that possible to create table in run time by using EF Code-first? i could create my models class in run time by using C# CodeDOM(reflection) but i couldn't set the dbSet properties of my Dbcontext class in run time. whats your idea? whats the best solution to create table dynamically in run time?... some ones said to my that the only way is using classic ADO.Net.
推荐答案
是的,你可以这样做.
您可以使用查找类来做到这一点:
You can do that using Finding the Classes :
[AttributeUsage(AttributeTargets.Class)]
public class PersistentAttribute : Attribute
{
}
现在您可以向 context
的 OnModelCreating
方法添加一些逻辑,以扫描程序集并添加具有 [Persist]
属性的任何类如下图.
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
更新:如何查询动态表?
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
这篇关于使用实体框架 Code-First 创建表,运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!