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; } } }
.Net5使用EFCore CodeFirst模式 数据迁移并实现DBContext依赖注入
标签:方法 text pwd int 依赖项 ase migration turn alt
查看更多关于.Net5使用EFCore CodeFirst模式 数据迁移并实现DBContext依赖注入的详细内容...