.NET Core2.2版本使用EF框架CodeFirst方式初探

写在前面

相信大家在.NET Framework中对EF框架的使用频率还是比较高的,但是随着微软爸爸全面转向跨平台的.NET Core后越来越多的.NET开发者也开始拥抱这个全新的跨平台解决方案。本人在使用过程中发现在.NET Core中使用新版本的EFCore框架与原有使用方式略有不同,所以在这里以CodeFirst为例为大家带来一个Demo。

本项目中包含一个TryEFCore(.NET Core Web项目)和Responsibility(.NET Core类库)。

准备工作:

  1. 首先保证环境支持.NET Core。
  2. 创建一个.NET Core Web项目
  3. 创建一个.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>

看下效果:

非常完美

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章