dotnet / dotnet/Scaffolding

Incorrect bind properties, parameter name and DbSet name when scaffolding MVC Controller with views

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

Description

### Background

I am scaffolding using the new _dotnet scaffold_ tool, version 9.0.1. I am scaffolding _MVC_ -> _MVC Controller with views, using Entity Framework (CRUD)_. The source is the DB context and model included below. I am using _BooksController_ as the generated controller name.

Test project: [Example.zip](https://github.com/user-attachments/files/22084476/Example.zip)

### Issues

As seen in the generated code:
* Properties _ReleaseDate,Genre,Price_ are hallucinated, _Summary,Published_ are missing
* The parameter in _Create_ and _Edit_ is named _movie_ but the rest of the code uses _book_ as expected
* The generated code does not use the DbSet names from the DB context
* The views directory is named after the model, not the controller, so the controller did not find any views. (_Book_ vs _Books_)

### Source DB context

```C#
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
}

public DbSet Authors => Set();
public DbSet Books => Set();
public DbSet Reviews => Set();
}
```

### Source model

```C#
using System.ComponentModel.DataAnnotations;

namespace Example.Models
{
public class Book
{
public Book() {}

public int Id { get; set; }

[Required]
[StringLength(200)]
public string Title { get; set; } = string.Empty;

[StringLength(1000)]
public string Summary { get; set; } = string.Empty;

[DataType(DataType.Date)]
public DateTime Published { get; set; }
}
}
```

### Generated Create action
```C#
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind("ID,Title,ReleaseDate,Genre,Price")] Book movie)
{
if (ModelState.IsValid)
{
_context.Add(book);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(book);
}
```

### Generated Edit action

```C#
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Edit(int? id, [Bind("ID,Title,ReleaseDate,Genre,Price")] Book movie)
{
if (id != book.Id)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(book);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BookExists(book.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(book);
}
```

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.