.Net5使用EFCore CodeFirst模式 數據遷移並實現DBContext依賴注入


1.新建空白解決方案 EFCoreDemo ,添加一個Api項目 EFCoreDemo.API 和一個類庫 EFCoreDemo.Model

2.EFCoreDemo.Model 中使用NuGet添加依賴項 :

  • Microsoft.EntityFrameworkCore

  • Microsoft.EntityFrameworkCore.Tools

  • Microsoft.EntityFrameworkCore.SqlServer (我這里使用的是SqlServer數據庫,根據不同的數據庫自行選擇)

EFCoreDemo.Api 中使用NuGet添加依賴項 :

  • Microsoft.EntityFrameworkCore.Design

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;
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM