ASP.NET EF has a Route Model Binding, as in Laravel?

Viewed 83

After Laravel, I try to find the same functionality in every framework. Right now I'm switching to ASP.NET, but I'm worried that I can't use something as handy as Route Model Binding. It's so easy to do CRUD or implement auth Policy. Is there something like that in NET? For example:

class UserController extends Controller
{
    public function delete(User $user)
    {
       $user->delete();
    }
}
1 Answers

The CRUD controller pattern in .NET looks like this:

class UserController : Controller
{
    MyDbContext db;
    public UserController(MyDbContext db)
    {
       this.db=db;
    }
    public async Task Delete(User user)
    {
       db.Users.Remove(user);
       await db.SaveChangesAsync();
    }
}

Entities don't have a reference to the database in EF. They are Plain-Old-C#-Objects (POCOs), so you need to use DI to inject an instance of your DbContext.

Routing is a separate matter, see especially Routing to controller actions in ASP.NET Core.

Related