我可以让我的上下文从抽象类继承并首先使用代码吗?

本文关键字:代码 我的 上下文 继承 抽象类 我可以 | 更新日期: 2023-09-27 17:56:06

为了保持上下文干净简单,我在抽象类中放置了很多逻辑,并使我的上下文继承自它。

我在这里看到了这种方法,但现在由于我的类不再直接从DBContext继承,因此我无法创建迁移。

我的抽象类是

public abstract class MyContext : DbContext
{
    public MyContext(string connString)
        : base(connString)
    {
    }
   public override int SaveChanges()
    {
        // custom code here
    }
}

现在,当我尝试通过在 PM 控制台键入 add-migration 来创建迁移时,我收到一个错误,指示找不到从DBContext继承的类

PM 控制台显示

PM> add-migration kirsten2 No migrations configuration type was found in the assembly 'DataLayer'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration). 
PM> Enable-Migrations No context type was found in the assembly 'DataLayer'. 

我可以让我的上下文从抽象类继承并首先使用代码吗?

如果在 EF 存储库中搜索此错误消息("未找到迁移配置类型"),则会在 EntityFramework/Properties/Resources.cs 文件中找到此资源:

/// <summary>
/// A string like "No migrations configuration type was found in the assembly '{0}'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration)."
/// </summary>
internal static string AssemblyMigrator_NoConfiguration(object p0)
{
    return EntityRes.GetString(EntityRes.AssemblyMigrator_NoConfiguration, p0);
}

下一步是搜索AssemblyMigrator_NoConfiguration使用情况,你会发现在 EntityFramework/Migrations/Design/ToolingFacade.cs 中只出现了一次:

private DbMigrationsConfiguration FindConfiguration()
{
    var configurationType = FindType<DbMigrationsConfiguration>(
        ConfigurationTypeName,
        types => types
                     .Where(
                         t => t.GetConstructor(Type.EmptyTypes) != null
                              && !t.IsAbstract
                              && !t.IsGenericType)
                     .ToList(),
        Error.AssemblyMigrator_NoConfiguration,
        (assembly, types) => Error.AssemblyMigrator_MultipleConfigurations(assembly),
        Error.AssemblyMigrator_NoConfigurationWithName,
        Error.AssemblyMigrator_MultipleConfigurationsWithName);
    return configurationType.CreateInstance<DbMigrationsConfiguration>(
        Strings.CreateInstance_BadMigrationsConfigurationType,
        s => new MigrationsException(s));
}

我认为现在跟踪错误并修复它会更容易。

我已经在源代码上对其进行了测试,并且消息无关紧要,事实证明rel原因是app.config中的目标框架标记。

这是有正确答案的类似问题:升级到 .NET 4.5 和 EF 5 后,"启用迁移"失败

有趣的是,如果您运行分别完全指向上下文类名和配置类名的启用迁移和添加迁移,它工作正常。但是提到的解决方案是正确的解决方案,也更容易:-)