寫在前面
相信大家在.NET Framework中對EF框架的使用頻率還是比較高的,但是隨着微軟爸爸全面轉向跨平臺的.NET Core後越來越多的.NET開發者也開始擁抱這個全新的跨平臺解決方案。本人在使用過程中發現在.NET Core中使用新版本的EFCore框架與原有使用方式略有不同,所以在這裏以CodeFirst爲例爲大家帶來一個Demo。
本項目中包含一個TryEFCore(.NET Core Web項目)和Responsibility(.NET Core類庫)。
準備工作:
- 首先保證環境支持.NET Core。
- 創建一個.NET Core Web項目
- 創建一個.NET Core 類庫
正式開始
首先,在類庫Responsibility中創建Tb_User類
using System;
using System.ComponentModel.DataAnnotations;
namespace Responsibility
{
public class Tb_User
{
[Key]
public string ID { get; set; }
public string UserName { get; set; }
public string Sex { get; set; }
public DateTime CreateTime { get; set; }
}
}
創建DbContex數據庫上下文QMDbContext(名字任取)
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace Responsibility
{
public class QMDbContext:DbContext
{
public QMDbContext(DbContextOptions<QMDbContext> options) : base(options)
{
}
//建立表與模型的映射關係
public DbSet<Tb_User> User { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
這時會報錯,由於類庫項目中沒有引用相關依賴,注意切換項目
在程序包管理控制檯輸入 命令: Install-Package Microsoft.EntityFrameworkCore.SqlServer
這樣在該類庫項目中的任務都已經完成。
在Web項目中,我們需要在在Startup.cs中加入以下代碼並引入頭文件using Microsoft.EntityFrameworkCore;
//配置EF框架的數據庫連接,在服務中添加數據上下文
services.AddDbContext<QMDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("QMConnection"), b => b.MigrationsAssembly("Responsibility")));
在appsettings.json中加入連接字符串
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"QMConnection": "Server=你的數據庫地址;Database=QMDB;User ID=sa;Password=你的密碼"
}
}
至此所有準備工作完成,在程序包命令切換到Responsibility中,執行Add-Migration FirstMigration 查看數據庫中是否多了自己添加的數據庫,如果有就已經操作成功。
簡單測試:
在Web項目中Controllers文件夾創建控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Responsibility;
namespace TryEFCore.Controllers
{
public class DefaultController : Controller
{
//構造函數注入上下文
private readonly QMDbContext _context;
public DefaultController(QMDbContext Context)
{
_context = Context;
}
public IActionResult Index()
{
return View(_context.User.ToList());
}
}
}
在Views文件夾中創建Default文件夾創建Index視圖
@model IEnumerable<Responsibility.Tb_User>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
@Html.DisplayNameFor(model => model.Sex)
</th>
<th>
@Html.DisplayNameFor(model => model.CreateTime)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sex)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreateTime)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
看下效果:
非常完美