4Manuals

  • PDF Cloud HOME

网络核心:使用变量类型声明新的DbContext Download

    获取Hough线的交点OpenCV C ++ 如何将字符串“ text1”设置为包含项目text1,text2,test3的组合框的选定项目? 为什么System.Net.Mail.MailAddress构造函数在域部分中解析带有斜杠“ /”的电子邮件? Android 10,API29:在应用程序文件夹中使用C ++库编写文件会使应用程序崩溃 Unity-LineRenderer没有出现在版本(2D)上 按下按钮后,电话中未显示通知 ASP.net,使用WebConfig httpErrors重定向到区域内的控制器不起作用 获取会议室详细信息 我们如何将参数Line转换为Station? 网络核心:查找实体框架核心的主键和反射

我如何声明DbContextOptionsBuilder,其中DbContext存储在一个变量中(在这种情况下,dbContext的真实名称是“ OnlineShoppingStore”,但存储在下面的两个变量中。

var dbContextType = dbContextAssembly.GetTypes().Where(d => d.BaseType.Name == "DbContext").First();
var businessDbContext = Activator.CreateInstance(dbContextType) as DbContext;
DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder();

// Attempting Line Below
var options = new DbContextOptionsBuilder<dbContextType>().UseInMemoryDatabase(databaseName: "Test").Options;
  

错误:dbContextType是一个变量,但是像类型一样使用。

最终目标是根据上述程序集中的类型声明一个新的DbContext。

示例:

var onlineStoreContext = new OnlineStoreContext(options)

1 个答案:

答案 0 :(得分:0)

您快到了。您可以使用以下方法创建通用类型的实例:

Type dbContextType = typeof(MyDbContext);
// 1st get type of Generic object
Type dbContextOptionsBuilderType = typeof(DbContextOptionsBuilder<>);
// 2nd call "MakeGenericType" method by passing the "T" type
Type dbContextOptionsBuilderGenericType = dbContextOptionsBuilderType.MakeGenericType(dbContextType);
// 3rd create an instance by using "Activator.CreateInstance"
DbContextOptionsBuilder dbContextOptionsBuilderInstance = Activator.CreateInstance(dbContextOptionsBuilderGenericType) as DbContextOptionsBuilder;

DbContextOptions dbContextOptions = dbContextOptionsBuilderInstance.UseInMemoryDatabase(databaseName: "Test").Options;

“ How to use local variable as a type? Compiler says "it is a variable but is used like a type"”是原始解决方案。



Similar searches
    heroku在每次部署期间都会继续安装django软件包 从集合中删除(如果为空) 如何在Laravel控制器中获取复选框值? 找不到栏图标的侦听器 如何总计包含持续时间到数分钟的数组?