.Net5使用EFCore CodeFirst模式 数据迁移并实现DBContext依赖注入

时间:2021-04-10 13:06:42   收藏:0   阅读:0

1.新建空白解决方案 EFCoreDemo ,添加一个Api项目 EFCoreDemo.API 和一个类库 EFCoreDemo.Model

技术图片

2.EFCoreDemo.Model 中使用NuGet添加依赖项 :

EFCoreDemo.Api 中使用NuGet添加依赖项 :

技术图片

3.EFCoreDemo.Model中创建 Models文件夹 ,添加User实体类

技术图片

public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

4.EFCoreDemo.Model中添加数据库上下文 EFCoreContext 类

技术图片

using EFCoreDemo.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace EFCoreModel
{
    public class EFCoreContext : DbContext
    {
        public EFCoreContext(DbContextOptions<EFCoreContext> options) : base(options)
        {

        }
        public DbSet<User> Users { get; set; }
    }
}

5.appsettings 文件中配置连接字符串(改成自己的)

技术图片

 "ConnectionStrings": {
    "Default": "Server=.;DataBase=Test;uid=sa;pwd=123456"
  }

6.Startup 的 ConfigureServices 方法中注入

技术图片

services.AddDbContext<EFCoreContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("Default")));

7.将 EFCoreDemo.API 设为启动项目,将程序包管理控制台默认项目设为 EFCoreDemo.Model

? 执行命令 add-migration i1(i1是迁移版本名称,可以自定义)

技术图片

技术图片

8.程序包管理控制台执行命令 update-database 更新数据库,然后到数据库中查看,可以看到已经执行成功

技术图片

9.经过以上步骤,就可以在项目中使用了,新建一个 User控制器测试一下

using EFCoreDemo.Model.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EFCoreDemo.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly EFCoreContext _db;

        public UserController(EFCoreContext eFCoreContext)
        {
            this._db = eFCoreContext;
        }
        [HttpGet]
        public List<User> GetUsers()
        {
            List<User> userList = _db.Users.ToList();
            return userList;  
        }
        [HttpPost]
        public bool PostUser([FromForm] User user)
        {
            _db.Users.Add(user);
            bool b = _db.SaveChanges()>0;
            return b;
        }
    }
}

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!