Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何访问ASP.Net Core2 cshtml文件(视图)中的数据库_C#_Asp.net Core 2.0_Dbcontext - Fatal编程技术网

C# 如何访问ASP.Net Core2 cshtml文件(视图)中的数据库

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>

我正在寻找一种在ASP.NETCore2的视图页面(cshtml)中加载(或访问)数据库表的方法。 我曾经通过从DB上下文创建一个对象来访问数据库。例如,为了在MVC项目中填充一个表(通过使用Razor引擎),我可以创建一个对象和一个表,如下所示:

<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")