Search code examples
c#asp.net-coreentity-framework-coreminimal-apisasp.net-core-scaffolding

Scaffolding Minimal Api with a separate DbContext project throws error "Could not load information for ..."


I have a solution name BugDemo consisting of 2 projects. Here is the github repo.

  • a class library named Data.
  • an Asp.Net Core Minimal Api named Api referencing Data project. I set Api project as the startup project.

I use User Secret to share secret.json between these 2 projects.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=BugDemoDb;Integrated Security=true;TrustServerCertificate=true"
  }
}

I successfully generated the database with the following (executed from solution directory):

dotnet ef migrations add Initialization --startup-project Data --project Data
dotnet ef database update --startup-project Data

I attempted to invoke scaffolding with the following:

$env:codegen_trace=1 
dotnet-aspnet-codegenerator minimalapi --project api

And I got the following errors:

Line: minimalapi --project api Trace: Executing external command: dotnet msbuild C:\Projects\BugDemo\api\Api.csproj /t:EvaluateProjectInfoForCodeGeneration /p:OutputFile=C:\Users\amd\AppData\Local\Temp\wybiwf1d.d4d;CodeGenerationTargetLocation=C:\Users\amd.dotnet\tools.store\dotnet-aspnet-codegenerator\7.0.0-rc.1.22452.2\dotnet-aspnet-codegenerator\7.0.0-rc.1.22452.2\tools\net7.0\any;Configuration=Debug -restore

Building project ... Trace: Executing external command: dotnet build C:\Projects\BugDemo\api\Api.csproj --configuration Debug --framework net7.0

Trace: Executing external command: dotnet exec --runtimeconfig C:\Projects\BugDemo\api\bin\Debug\net7.0\Api.runtimeconfig.json --depsfile C:\Projects\BugDemo\api\bin\Debug\net7.0\Api.deps.json C:\Users\amd.nuget\packages\microsoft.visualstudio.web.codegeneration.design\7.0.0-rc.1.22452.2\lib\net7.0\dotnet-aspnet-codegenerator-design.dll --no-dispatch --port-number 62322 minimalapi --project api --dispatcher-version 7.0.0-rc.1.22452.2

Trace: Command Line: --no-dispatch --port-number 62322 minimalapi --project api --dispatcher-version 7.0.0-rc.1.22452.2 Scaffolding failed. Could not load information for project ..\Data\Data.csproj Trace: at Microsoft.VisualStudio.Web.CodeGeneration.Utils.RoslynWorkspaceHelper.GetProjectReferenceInformation(IEnumerable1 projectReferenceStrings) at Microsoft.VisualStudio.Web.CodeGeneration.Utils.RoslynWorkspace..ctor(IProjectContext projectInformation, String configuration) at Microsoft.VisualStudio.Web.CodeGeneration.Design.CodeGenCommandExecutor.AddFrameworkServices(ServiceProvider serviceProvider, IProjectContext projectInformation) at Microsoft.VisualStudio.Web.CodeGeneration.Design.CodeGenCommandExecutor.Execute(Action1 simModeAction) at Microsoft.VisualStudio.Web.CodeGeneration.Design.Program.<>c__DisplayClass4_0.<b__0>d.MoveNext() RunTime 00:00:12.60

Project Api

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

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>b3fdc987-781a-4fd4-853d-e279524cb5c6</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.0-rc.1.22427.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0-rc.1.22426.7" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.0-rc.1.22426.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.0-rc.1.22452.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
  </ItemGroup>

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

</Project> 


using Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(opts =>
{
    opts.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();


if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/", async (AppDbContext ctx) =>
{
    return await ctx.Students.ToListAsync();
});

app.Run();

Project Data

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

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <UserSecretsId>b3fdc987-781a-4fd4-853d-e279524cb5c6</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.0-rc.1.22426.7">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.0-rc.1.22426.7" />
    <PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0-rc.1.22426.10" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.0-rc.1.22452.2" />
  </ItemGroup>

</Project>


namespace Data;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; } = default!;
}


using Microsoft.EntityFrameworkCore;

namespace Data;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> opts) : base(opts) { }
    public DbSet<Student> Students { get; set; }
    protected override void OnModelCreating(ModelBuilder mb)
    {
        base.OnModelCreating(mb);
        mb.Entity<Student>().HasData(new Student[]
        {
            new Student{ Id=1,Name="Albert Einstein"},
            new Student{ Id=2,Name="Isaac Newton"},
            new Student{ Id=3,Name="Blaise Pascal"},
            new Student{ Id=4,Name="Nicola Tesla"}
        });
    }
}



using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace Data;

public class AppDesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        IConfiguration config = new ConfigurationBuilder()
             .AddUserSecrets<Data.AppDesignTimeDbContextFactory>()
             .Build();

        var opts = new DbContextOptionsBuilder<AppDbContext>();
        opts.UseSqlServer(config.GetConnectionString("DefaultConnection"));

        return new AppDbContext(opts.Options);
    }
}

Question

How to fix this issue?


Solution

  • The issue is fixed in Visual Studio version - 17.3.4 and above. Currenly the latest one is 17.3.4 The problem was that during scaffolding the CodeGeneration library was downgraded from 6.0.10 to 6.0.9. With the fix it is not downgrading anymore and it works properly.

    https://github.com/dotnet/Scaffolding/issues/2034