例如,以下是展示Products表和Categories表的模型的视图:
CREATE VIEW ProductCategoryView AS
SELECT Product.Name AS ProductName, Category.Name AS CategoryName
FROM Product
JOIN Category ON Product.CategoryId = Category.Id
在ASP.NET Core 6中创建一个新的控制器(Controller),这个控制器的名称应该与要展示的模型的名称相关联,例如,在此示例中,我们需要一个名为“ProductCategoryController”的控制器。
在控制器中,添加一个Action,这个Action将使用LINQ查询来获取视图(View)并将其作为数据传递给相关的视图(View)文件。
例如,以下是获取ProductCategoryView视图的Action:
public IActionResult ProductCategoryList()
{
using (var context = new MyDbContext()) // MyDbContext是你自己的DbContext
{
var model = context.ProductCategoryView.ToList(); // 使用LINQ查询获取视图数据
return View(model); // 将视图数据作为参数传递给视图文件
}
}
在视图文件中,使用Razor语法访问视图数据并将其呈现到屏幕上。
例如,以下是展示ProductCategoryView视图数据的Razor代码:
@model List
Product Name
Category Name
@foreach (var item in Model)
{
@item.ProductName
@item.CategoryName
}
最后,我们可以在浏览器中访问我们的ASP.NET Core 6应用程序,并访问ProductCategoryList Action来展示视图数据。