上次介绍了一下如何进行连接数据库,我们连了一个 SQL Server 试了试,感觉还是比较良好的。
但是有人说,不会数据库操作。什么怎么怎么查询,怎么怎么插入(上次不是演示了吗?),还有怎么怎么修改,对了删除不了怎么办。什么怎么样,该怎么办就怎么办——汪。。。
一、查:
查,是我们常用的操作。比如,向用户展示相关信息,相关的数据等等。怎么操作呢?我们来一步一步进行操作。
first:我们先把 Home/IndexController 与 View/index.cshtml 里面的进行修改,代码如下:
先改 HomeController:
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace testProject.Controllers
{
public class HomeController : Controller
{
Model.myDataBase db = new Model.myDataBase();
public IActionResult Index()
{
var userlist = from u in db.Users
select u;
ViewBag.userList = userlist;
ViewBag.userCount = userlist.Count();
return View();
}
}
}
1、Model.myDataBase db = new Model.myDataBase();
不必说了,我们先准备好数据库对象,以遍进行数据库操作,所以,我把其作为类的一个属性,而不是方法里面的变量。这样可以在需要时直接调用。
2、public IActionResult Index()
这就相当于原来 .net 里的 public ActionResult Index()。在 .net core 中,全是在 ActionResult 前面加个“I”。其它的都一样啦。
3、var userlist = from u in db.Users select u;
这个就是执行 Linq 进行查询操作。
4、ViewBag.xxx 就是向视图(View)进行数据传输,也就是向前端传输显示的内容。
我们已经知道了有“public IActionResult Index()”,就要在视图(View)中建立一个对应的 index.cshtml,那我们建立一下,具体代码如下:
Views/Home/index.cshtml
@{
ViewData["Title"] = "主页";
}
<style type="text/css">
.tableStyleBorder {
margin: 0px auto; margin-top: 30px; border-collapse: collapse; border: 1px solid Black;}
.tableStyleBorder th, .tableStyleBorder td {
min-width: 80px; text-align: center; padding: 8px; border: 1px solid Black;}
</style>
<table class="tableStyleBorder">
<tr>
<th>ID</th>
<th>姓名</th>
<th>创建时间</th>
</tr>
@if(0 < ViewBag.userCount)
{
@foreach (var item in ViewBag.userList)
{
<tr>
<td>@item.id</td>
<td>@item.name</td>
<td>@item.createtime</td>
</tr>
}
}
else
{
<tr>
<td colspan="3">没有数据</td>
</tr>
}
</table>
1、ViewBag.xxx 就是对应“控制器”(Controller 文件夹中的 CS 文件里)中的 ViewBag.xxx(见 HomeController.cs)。执行顺便是,先执行 控制器,得到的数据通过 ViewBag 传给 index.cshtml。
2、@if、@foreachÿ