首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Net核心:用变量类型声明新的DbContext

Net核心:用变量类型声明新的DbContext
EN

Stack Overflow用户
提问于 2019-12-31 03:46:57
回答 1查看 365关注 0票数 0

如何声明DbContextOptionsBuilder,其中DbContext存储在变量中(在本例中,dbContext的实名为"OnlineShoppingStore“,但存储在下面的两个变量中)。

代码语言:javascript
复制
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,给定来自上面程序集的类型。

示例:

代码语言:javascript
复制
var onlineStoreContext = new OnlineStoreContext(options)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-31 04:43:18

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

代码语言:javascript
复制
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"“是最初的解决方案。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59539329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档