dotnet / dotnet/aspnetcore

BindProperty attribute should support primary constructors with classes

Open
#58,205 0 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

In an ASP.NET Core Razor project, creating this class with a primary constructor

```csharp
public class Book(string title, string? publisher = default, int id = 0)
{
public int Id { get; set; } = id;

[StringLength(50)]
public string Title { get; set; } = title;

[StringLength(50)]
public string? Publisher { get; set; } = publisher;
}
```

succeeds in scaffolding creating Razor pages with EF Core.

This is the code from the Create page code-behind:

```csharp
public class CreateModel : PageModel
{
private readonly RazorPagesWithEFCore.Data.BooksContext _context;

public CreateModel(RazorPagesWithEFCore.Data.BooksContext context)
{
_context = context;
}

public IActionResult OnGet()
{
return Page();
}

[BindProperty]
public Book Book { get; set; } = default!;
```

Running the application fails with an `InvalidOperationException`:

> InvalidOperationException: Could not create an instance of type 'RazorPagesWithEFCore.Models.Book'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Record types must have a single primary constructor. Alternatively, set the 'Book' property to a non-null value in the 'RazorPagesWithEFCore.CreateModel' constructor.

### Describe the solution you'd like

Using a parameterless constructor as described with the error, the application runs. I would prefer to use the primary constructor. Using records, the error mentions it's ok using a primary constructor. This should be possible with a class as well (and scaffolding creates code successfully).

### Additional context

The alternative option mentioned in the error message "Alternatively, set the 'Book' property to a non-null value in the 'RazorPagesWithEFCore.CreateModel' constructor.", is not working. Assigning a non-null value to the `Book` property fails as well.

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.