C# 如何访问ASP.Net Core2 cshtml文件(视图)中的数据库
我正在寻找一种在ASP.NETCore2的视图页面(cshtml)中加载(或访问)数据库表的方法。 我曾经通过从DB上下文创建一个对象来访问数据库。例如,为了在MVC项目中填充一个表(通过使用Razor引擎),我可以创建一个对象和一个表,如下所示:C# 如何访问ASP.Net Core2 cshtml文件(视图)中的数据库,c#,asp.net-core-2.0,dbcontext,C#,Asp.net Core 2.0,Dbcontext,我正在寻找一种在ASP.NETCore2的视图页面(cshtml)中加载(或访问)数据库表的方法。 我曾经通过从DB上下文创建一个对象来访问数据库。例如,为了在MVC项目中填充一个表(通过使用Razor引擎),我可以创建一个对象和一个表,如下所示: <table > <thead> <tr > <th></th> </tr> </thead>
<table >
<thead>
<tr >
<th></th>
</tr>
</thead>
ProjectName.Models.ProjectNameEntities db = new ProjectName.Models.ProjectNameEntities();
var CustomerTableObject= db.Customer.ToList();
<tbody>
@foreach (var item in CustomerTableObject)
{
<tr>
<td ></td>
</tr>
}
</tbody>
</table>
ProjectName.Models.ProjectNameEntities db=新的ProjectName.Models.ProjectNameEntities();
var CustomerTableObject=db.Customer.ToList();
@foreach(CustomerTableObject中的变量项)
{
}
您不应该在视图中直接访问数据库。相反,可以使用视图组件。创建文件ViewComponents\CustomerTableViewComponent.cs
,如下所示:
public class CustomerTableViewComponent : ViewComponent
{
private readonly ProjectNameEntities _context;
public CustomerTableViewComponent(ProjectNameEntities context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<IViewComponentResult> InvokeAsync()
{
var customers = await _context.Customer.ToListAsync();
return View(customers);
}
}
最后,在要显示此表的位置添加行:
@await Component.InvokeAsync("CustomerTable")
@await Component.InvokeAsync("CustomerTable")