asp.net-core - “模型构建器”不包含“ApplyAllConfigurations”的定义?
问题描述
我正在关注这个 youtube视频,在34:05时,它是使用 EntityFramework Core 的 ASP.Net 核心的架构,他们正在展示一种扩展方法
modelBuilder.ApplyAllConfigurations();
我在我的代码中尝试了这个并且它抛出错误: 'ModelBuilder'不包含'ApplyAllConfigurations'的定义,并且找不到接受'ModelBuilder'类型的第一个参数的可访问扩展方法'ApplyAllConfigurations'(你是否缺少使用指令还是装配参考?
我错过了任何参考吗?如果没有,我该如何在我的项目中实现它?
解决方案
检查你的ApplyAllConfigurations
方法是否如下。我正在使用它并且它工作得很好。
public static class ModelBuilderExtensions
{
public static void ApplyAllConfigurations(this ModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces()
.Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))).ToList();
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.ApplyConfiguration(configurationInstance);
}
}
}
注意:确保此扩展方法和您DbContext
的在同一个程序集中。否则,在扩展方法中明确指定程序集名称。
推荐阅读
- swift - 如何将我自己的自定义 swift 文件导入项目?
- sql - SQL 表架构缺少关键数据 - 无法回答问题
- c++ - 三个数中的最大成对递减数
- android - 编译android Q内核时出现错误
- javascript - 使用 javascript 编辑 :not() 选择器
- python - 保存视频 OpenCV(python) - 保存多个视频
- javascript - Mozilla WebExtension:本地存储有效,但同步存储无效
- haskell - Stack (Haskell) 使用 GitHub Actions 构建源文件缓存
- ftp - 当通过 Atom 上的 Remote-FTP 下载时,服务器上根文件夹上的文件和文件夹会丢失第一个字符
- beautifulsoup - 使用 BeautifulSoup 查找嵌入信息