dotnet / dotnet/Scaffolding

`Could not get the reflection type for DbContext` when using `required` keyword in model

Open
#2,546 3 comments 1 reaction 0 assignees View on GitHub
area-scaffolding customer-reported
Dominant language
C#
Stars
818
Forks
260
Avg merge
1d 8h
Merged PRs (30d)
10

Description

I was following along with this [API tutorial](https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-7.0&tabs=visual-studio-code#:~:text=Run%20the%20following%20command%3A) when I came upon an odd exception. It took a bit of guess-and-check testing, but I narrowed it down to only occur when the `required` keyword is added (below is the example model).

The tutorial lists the .NET 7.0 SDK in the prerequisites. From what I've found in the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version), that should use C# 11 (which is when the `required` keyword [was introduced](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required)). Is this an issue with the `aspnet-codegenerator` tool, the documentation, or my own misunderstanding?

Code:
``` C#
namespace TodoApi.Models;

public class TodoItem
{
public long Id { get; set; }
public required string? Name { get; set; }
public bool IsComplete { get; set; }
}
```

Stack Trace:
```
$ dotnet aspnet-codegenerator controller -name TodoItemsController -async -api -m TodoItem -dc TodoContext -outDir Controllers
Building project ...
Finding the generator 'controller'...
Running the generator 'controller'...

Minimal hosting scenario!
Attempting to compile the application in memory.
Could not get the reflection type for DbContext : TodoApi.Models.TodoContext
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:09.75
```

### Include provider and version information

Microsoft.VisualStudio.Web.CodeGeneration.Design version: 7.0.0
Target framework: .NET 7.0
Operating system: Windows 11
IDE: VS Code 1.82.2

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.