1)引用
(1)Install-Package Microsoft.EntityFrameworkCore
(2)Install-Package Microsoft.EntityFrameworkCore.SqlServer
(3)Install-Package Microsoft.EntityFrameworkCore.Tools
(4)Install-Package Microsoft.EntityFrameworkCore.SqlServer.Desig
2)连接数据库获取实体类
1)新建Models 替换相应地址
Scaffold-DbContext "Data Source=.;Initial Catalog=MirrorPro;User ID=sa;Password=123" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
2)声明接口 ITodoItemService.cs
public interface ITodoItemService { /// <summary> /// 在一个task里存放TodoItem的列表 /// </summary> /// <returns></returns> Task<IEnumerable<AdminUser>> GetIncompleteItemsAsync(); }
3)实现接口 TodoItemService.cs
public class TodoItemService : ITodoItemService { private readonly MirrorProContext _context; public TodoItemService(MirrorProContext context) { _context = context; } public async Task<IEnumerable<AdminUser>> GetIncompleteItemsAsync() { var items = await _context.AdminUser .Where(x => x.IsAbort == false) .ToListAsync(); return items; } }
4)控制器依赖
private readonly ITodoItemService _todoItemService;
public TodoController(ITodoItemService todoItemService) { _todoItemService = todoItemService; }
public async Task<IActionResult> Index() { //获取异步参数 var todoItems = await _todoItemService.GetIncompleteItemsAsync(); return View(todoItems); }
5)Startup.cs 修改如下
public void ConfigureServices(IServiceCollection services) { //数据库连接 services.AddDbContext<MirrorProContext>(); services.AddMvc(); //把你的服务放进一个 可用服务集合 scoped 每次需要FakeTodoItemService类的对象时,就创建一个新的出来 //告诉Core你的接口实现应对多个接口实现的情况 services.AddScoped<ITodoItemService, TodoItemService>(); }