dotnet / Scaffolding

Code generators to speed up development.
MIT License
638 stars 228 forks source link

Scaffolding API endpoints is not working with primary constructors #2570

Closed christiannagel closed 1 week ago

christiannagel commented 11 months ago

Using Visual Studio, scaffolding API endpoints with read/write endpoints, using EF Core fails when using primary constructors using C# 12.

I've already reported this with the Visual Studio Developer Community, but I think this GitHub repo is a better place: https://developercommunity.visualstudio.com/t/NET-8:-scaffolding-API-endpoints-with-r/10505296

Versions: .NET: 8.0.100-rc.2.23502.2 Visual Studio: 17.8.0 Preview 6.0

  1. Create a new Web API, don’t select “use controllers” (using controllers probably has the same issues)
  2. Add a model type using a primary constructor:
public class Book(int id, string title, string? publisher = default)
{
    public int Id { get; set; } = id;
    public string Title { get; set; } = title;
    public string? Publisher { get; set; } = publisher;
}
  1. Add | New Scaffolded Item
  2. Select Common, API --> API with read/write endpoints, using Entity Framework
  3. Click Add
  4. Select the model class Book
  5. Click on the + with the Endpoints class, click Add
  6. Click the + with the DbContext class, click Add
  7. Click Add to finish the dialog

This results in an exception, error creating the DbContext, CS1514, expects { instead of the primary constructor.

As refactoring methods are available to use this new constructor, I expect this constructor to work with scaffolding.

See the project https://github.com/christiannagel/issues-scaffoldingapi/tree/main/PrimaryConstructor for a simple test.

Using an EF Core context with a primary constructor

When adding an EF Core context with a primary constructor, another error occurs:

  1. Add a new class BooksContext with a primary constructor:
public class BooksContext(DbContextOptions<BooksContext> options) : DbContext(options)
{
    public DbSet<Book> Book => Set<Book>();
}
  1. Repeat the steps 3.-7., with step 8. use the existing BooksContext class
  2. Use the existing DbContext class
  3. Click Add, then the error Sequence contains no elements is shown

See this project as a start with EF Core primary constructor: https://github.com/christiannagel/issues-scaffoldingapi/tree/main/PrimaryConstructor2

Again, I would expect this to work with primary constructors.

christiannagel commented 2 weeks ago

It looks like this is fixed and can be closed. I verified it's working now using

The problem with identifiers named with Id still exists: #2576

deepchoudhery commented 1 week ago

Cool tyty, fixing other issues soon as well.