【问题标题】:Cannot find DbContext class using dotnet ef migrations add Initial -s <project> -c <full class name from referenced project> -o <output dir>使用 dotnet ef migrations add Initial -s <project> -c <full class name from referenced project> -o <output dir> 找不到 DbContext 类
【发布时间】:2020-06-03 14:35:08
【问题描述】:

我正在尝试学习如何使用 dotnet core Entity Framework 生成迁移。

我有一个 ASP.NET Core Web API 项目,它引用了两个项目,每个项目都包含一个 DBContext。

我已经成功地使用以下方法为一个 dbcontext 生成了迁移:

dotnet ef migrations add Initial -s <startup_project> -c <fully qualified class name from referenced project> -o <output dir>

但是,对于第二个 DbContext,它无法找到带有消息的 DbContext: No DbContext named 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext' was found.

被引用项目的项目文件具有正确引用内容的路径:

<Project Sdk="Microsoft.NET.Sdk">

  <ItemGroup>
    <ProjectReference Include="..\EventBus\EventBus.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

</Project>

ASP.NET Core Web API 启动项目的项目文件为:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <ItemGroup>
    <ProjectReference Include="..\Courses.Domain\Courses.Domain.csproj" />
    <ProjectReference Include="..\Courses.Infrastructure\Courses.Infrastructure.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\WebHost.Customization\WebHost.Customization.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Npgsql" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="3.0.5" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="3.0.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="MediatR" Version="8.0.0" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql" Version="4.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Http" Version="5.2.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.Reflection" Version="4.3.0" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>


</Project>

找不到的上下文类的源码是:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF
{
    public class IntegrationEventLogContext : DbContext
    {       
        public IntegrationEventLogContext(DbContextOptions<IntegrationEventLogContext> options) : base(options)
        {
        }

        public DbSet<IntegrationEventLogEntry> IntegrationEventLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {          
            builder.Entity<IntegrationEventLogEntry>(ConfigureIntegrationEventLogEntry);
        }

        void ConfigureIntegrationEventLogEntry(EntityTypeBuilder<IntegrationEventLogEntry> builder)
        {
            builder.ToTable("IntegrationEventLog");

            builder.HasKey(e => e.EventId);

            builder.Property(e => e.EventId)
                .IsRequired();

            builder.Property(e => e.Content)
                .IsRequired();

            builder.Property(e => e.CreationTime)
                .IsRequired();

            builder.Property(e => e.State)
                .IsRequired();

            builder.Property(e => e.TimesSent)
                .IsRequired();

            builder.Property(e => e.EventTypeName)
                .IsRequired();
        }
    }
}

ASP.NET Core Web API项目的Startup.cs添加DB Contexts如下:

services.AddEntityFrameworkNpgsql()
                   .AddDbContext<CourseContext>(options =>
                   {
                       options.UseNpgsql(configuration["ConnectionString"],
                           npgsqlOptionsAction: sqlOptions =>
                           {
                               sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                               sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                           });
                   },
                       ServiceLifetime.Scoped  //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   );

            services.AddDbContext<IntegrationEventLogContext>(options =>
            {
                options.UseNpgsql(configuration["ConnectionString"],
                                     npgsqlOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency 
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                                     });
            });

是否可以从启动项目中为许多 DbContext 子类生成迁移?

如果是这样,找不到 DBContext 类的潜在原因是什么?

【问题讨论】:

    标签: .net-core entity-framework-core


    【解决方案1】:

    通过实现IDesignTimeDbContextFactory 的实例解决了这个问题。看了this后找到了这个解决方案

    现在当我跑步时...

    dotnet ef migrations add Initial -s &lt;startup_project&gt; -c &lt;fully.qualified.context.class.name&gt; -o &lt;output dir&gt;

    EntityFrameworkCore 定位我的第二个上下文类。

    【讨论】:

      【解决方案2】:

      问题是您试图从指向一个数据库的两个不同 DbContext 创建一个代码优先数据库 - 只有一个上下文可以做到这一点。

      我建议您制作一个只负责创建数据库的通用 DbContext。然后,您可以创建包含大型子集的真实应用程序上下文。

      是否可以从启动项目中为许多 DbContext 子类生成迁移?

      可以为许多 DbContext 子类生成迁移,以防它们指向不同的数据库。

      找不到 DBContext 类的潜在原因是什么?

      从您显示的错误中,我看到您正在寻找命名空间,而不是当前的 DbContext 类。

      “dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF”应为“dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext”

      【讨论】:

      • +10 哎呀,复制和粘贴错误没有将完整的命名空间复制到问题中……再次尝试以防万一,但仍然找不到上下文类,同样的消息。基于Microsoft's eshopContainers上的代码
      猜你喜欢
      • 2022-01-08
      • 2022-08-22
      • 1970-01-01
      • 2016-10-07
      • 2022-07-19
      • 1970-01-01
      • 2022-12-27
      • 2022-01-08
      • 2014-12-07
      相关资源
      最近更新 更多