我有一个DbContext,我需要从DLL动态加载,因为Db上下文会更改,并且需要在应用程序运行时进行编辑,但是由于似乎需要传递,因此我似乎无法创建该上下文的实例上下文选项。此代码如下。
Assembly reporting = Assembly.LoadFile(pathString);
var defaultContext = reporting.GetType("Reporting.DefaultContext");
var dbContext = Activator.CreateInstance(defaultContext, new
object[] { /*need to pass in the contructor here*/ }) as DbContext;
而且我的编译上下文非常标准,下面对此进行了修改,以供参考
public class DefaultContext : DbContext
{
public DefaultContext(DbContextOptions<DefaultContext> options)
: base(options)
{ }
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().ToTable("Students ", "core")
.AllProperties().ForEach(x => x.IsRequired());
modelBuilder.Entity<Course>().ToTable("Courses", "core")
.AllProperties().ForEach(x => x.IsRequired());
}
}
关于反射,我经验不足。
这是尝试实现此目标的最佳方法,还是应该创建一种在DLL上调用以返回上下文的方法?
如果没有,我没有上下文时如何通过DbContextOptions实例进行传递?
旁注,这是一个Asp.Net Core 2.0 MVC项目。
编辑:当改为将空的obj数组传递给创建实例时,如下所示,我得到了一个缺少的方法异常(未找到构造函数)
var dbContext = Activator.CreateInstance(defaultContext, new object[] { new object[0] }) as DbContext;
而如果我不传递第二个obj参数,则会得到相同的异常,但会显示消息“为此对象未定义无参数的构造函数”,所以现在我很迷路,因为显然有一个构造函数。
基本上,问题是如何DbContextOptions<DefaultContext>
通过反射创建/获取实例。为此,您可以先通过构建一个通用类型MakeGenericType
,然后将该类型用作的参数Activator.CreateInstance
。
所以有
var dbContextType = reporting.GetType("Reporting.DefaultContext");
像这样的东西:
var optionsType = typeof(DbContextOptions<>).MakeGenericType(dbContextType);
var options = (DbContextOptions)Activator.CreateInstance(optionsType);
var dbContext = (DbContext)Activator.CreateInstance(dbContextType, options);
但是,DbContextOptions<TDbContext> options
构造函数参数的全部目的是允许从外部配置db上下文(例如数据库提供程序,连接字符串等),而不是在内部进行自我配置OnModelConfiguring
,在这种情况下,派生的db上下文将仅具有无参数构造函数。
因此,最好创建DbContextOptionsBuilder<DefaultContext
实例,使用Fluent APi对其进行配置,然后将Options
属性(这是预期的DbContextOptions<DefaultContext
类型)传递给DefaultContext
构造函数。例如
var optionsBuilderType = typeof(DbContextOptionsBuilder<>).MakeGenericType(dbContextType);
var optionsBuilder = (DbContextOptionsBuilder)Activator.CreateInstance(optionsBuilderType);
string connectionString = ...;
optionsBuilder.UseSqlServer(connectionString);
var dbContext = (DbContext)Activator.CreateInstance(dbContextType, optionsBuilder.Options);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句