首页 > 解决方案 > “模型构建器”不包含“ApplyAllConfigurations”的定义?

问题描述

我正在关注这个 youtube视频,在34:05时,它是使用 EntityFramework Core 的 ASP.Net 核心的架构,他们正在展示一种扩展方法

    modelBuilder.ApplyAllConfigurations();

我在我的代码中尝试了这个并且它抛出错误: 'ModelBuilder'不包含'ApplyAllConfigurations'的定义,并且找不到接受'ModelBuilder'类型的第一个参数的可访问扩展方法'ApplyAllConfigurations'(你是否缺少使用指令还是装配参考?

我错过了任何参考吗?如果没有,我该如何在我的项目中实现它?

标签: asp.net-coreentity-framework-coredbcontextef-fluent-apief-model-builder

解决方案


检查你的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的在同一个程序集中。否则,在扩展方法中明确指定程序集名称。


推荐阅读