1、新建ASP.NET Core Web應用程式 2、從NuGet下載安裝以下工具包 Microsoft.EntityFrameworkCore Microsoft.EntityFrameworkCore.SqlServer Microsoft.EntityFrameworkCore.Tools M ...
1、新建ASP.NET Core Web應用程式
2、從NuGet下載安裝以下工具包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer.Design
3、然後,我們在VS的工具選項中,選擇NuGet包管理器,選擇程式包管理控制台(其中Models2是輸出文件夾)
Scaffold-DbContext "Server=.;database=test1;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
4、這裡面就是你的上下文對象和相關的實體類了
5、註釋上下文對象里的固化連接字元串
6、在配置文件里添加資料庫連接字元串:
"ConnectionStrings": { "SqlServer": "Server=.;database=test;Trusted_Connection=True;" },
7、然後我們在Startup中註入我們的上下文對象和獲取資料庫連接串
//註入上下文對象
services.AddDbContext<testContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));
8、創建控制器,代碼如下
public class FirstController : Controller
{
//構造函數註入上下文
private readonly testContext _context;
public FirstController(testContext Context)
{
_context = Context;
}
// GET: /<controller>/
public IActionResult Index(int? id)
{
base.ViewData["User1"] = new CurrentUser()
{
Id = _context.TestAutoid.Find(1).Autoid1,
Name = _context.TestAutoid.Find(1).Autoid2.ToString(),
Account = _context.TestAutoid.Find(1).Autoid3.ToString(),
Email = _context.TestAutoid.Find(1).Autoid4.ToString(),
Password = _context.TestAutoid.Find(1).Autoid5.ToString(),
};
base.ViewData["Something"] = 12345;
base.ViewBag.Name = "Eleven";
base.ViewBag.Description = "Teacher";
base.ViewBag.User = new CurrentUser()
{
Id = 7,
Name = "IOC",
Account = "限量版",
Email = "蓮花未開時",
Password = "落單的候鳥",
LoginTime = DateTime.Now
};
base.TempData["User"] = new CurrentUser()
{
Id = 7,
Name = "CSS",
Account = "季雨林",
Email = "KOKE",
Password = "落單的候鳥",
LoginTime = DateTime.Now
};//後臺可以跨action 基於session
if (id == null)
{
//return this.Redirect("~/First/TempDataPage");//未完待續
//return this.re
return this.Redirect("~/First/TempDataPage");
}
else
return View(new CurrentUser()
{
Id = 7,
Name = "一點半",
Account = "季雨林",
Email = "KOKE",
Password = "落單的候鳥",
LoginTime = DateTime.Now
});
}
}
9、創建相應的視圖如下:
@model NetCore2._2.MVC6.Models.CurrentUser
@using NetCore2._2.MVC6.Models;
@{
ViewBag.Title = "Index";
CurrentUser userViewData = ViewData["User1"] as CurrentUser;//ViewData需要類型轉換
CurrentUser userViewBag = ViewBag.User;//ViewBag直接用
CurrentUser userOther = ViewBag.User1;
}
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
@base.Model.Name
<p>@(((CurrentUser)ViewData["User1"]).Name)</p>
<p>@userViewData.Name</p>
<p>@userViewBag.Account</p>
<p>@userOther.Name</p>
<p>@(((CurrentUser)ViewBag.User).Name)</p>
<p>@(((CurrentUser)TempData["User"]).Name)</p>
<p>@base.Model.Name</p>
</div>
</div>
10、然後在運行我們的代碼.得到結果如下: