在ASP.NET Core中创建一个控制器(Controller)和一个模型(Model),用于访问和显示数据库中的数据。
在控制器中,使用Entity Framework Core来查询数据库并将数据传递给视图(View)。
示例代码:
// 控制器 public class UserController : Controller { private readonly ApplicationDbContext _context;
public UserController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
var users = _context.Users.ToList();
return View(users);
}
}
// 模型 public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
// 上下文
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions
public DbSet Users { get; set; }
}
示例代码:
@model List
Id | Name | Age |
---|---|---|
@user.Id | @user.Name | @user.Age |
示例代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}