.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 类库

.NET Core2.2版本使用EF框架CodeFirst方式初探_第1张图片

.NET Core2.2版本使用EF框架CodeFirst方式初探_第2张图片 

.NET Core2.2版本使用EF框架CodeFirst方式初探_第3张图片

正式开始

首先,在类库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 options) : base(options)
        {

        }
        //建立表与模型的映射关系
        public DbSet User { get; set; } 
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}

这时会报错,由于类库项目中没有引用相关依赖,注意切换项目

在程序包管理控制台输入 命令:     Install-Package Microsoft.EntityFrameworkCore.SqlServer

.NET Core2.2版本使用EF框架CodeFirst方式初探_第4张图片

这样在该类库项目中的任务都已经完成。

在Web项目中,我们需要在在Startup.cs中加入以下代码并引入头文件using Microsoft.EntityFrameworkCore;

//配置EF框架的数据库连接,在服务中添加数据上下文
            services.AddDbContext(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

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Index

Create New

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.UserName) @Html.DisplayNameFor(model => model.Sex) @Html.DisplayNameFor(model => model.CreateTime)
@Html.DisplayFor(modelItem => item.UserName) @Html.DisplayFor(modelItem => item.Sex) @Html.DisplayFor(modelItem => item.CreateTime) Edit | Details | Delete

看下效果:

.NET Core2.2版本使用EF框架CodeFirst方式初探_第5张图片

非常完美

 

你可能感兴趣的:(网站开发)