入坑.net core(三).net core api 3.1 反向工程 增删改查
话接上回:入坑.net core (二) swagger 配置
有兴趣的可以看一下,废话不多少,
接下来 教大家怎么用.net core 配置数据库,实现增删改查
1.点开VS扩展-》管理扩展
搜索 EF
安装EF Core Power Tools工具
在这里需要关闭VS工具,安装好再打开当前项目
2.右击项目 点击EF Core 工具 选择反向工程
选择版本,对应当前项目 我的是3.0
选择表,全选
配置实体和上下文,我这新建了Model类库,可以自行配置
配置好点确定
提示:没有找到Microsoft.EntityFrameworkCore库
管理NuGet程序包,配置
再配置以下库
(1)Microsoft.EntityFrameworkCore.SqlServer(连接sql server数据库的包)
(2)Microsoft.EntityFrameworkCore.Tools(命令行所需的库)
(3)Microsoft.EntityFrameworkCore.Design(vs code命令行所需的库,vs2019,不需要安装)
安装版本一定要看仔细
接着配置appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Information", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "ConnectionStrings": { "SQLServerConnection": "Data Source=.;Initial Catalog=vuetest;Integrated Security=True" } }
配置:Startup.cs
//连接sqlserver services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")); });
最后我们添加API控制器 放增删改查
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Web_API.Controllers
{
//路由设置
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly vuetestContext _context;
///
/// 初次判断
///
///
public UserController(vuetestContext context)
{
_context = context;
if (_context.User.Count() == 0)
{
_context.User.Add(new User { UserName = "admin", PassWord = "0837EB79BC250163", UserType = 0, Status = 0, Del = 0 });
_context.SaveChanges();
}
}
///
/// 异步获取
///
///
[HttpGet]
public async Task GetUser()
{
//ToListAsync在命名空间 using Microsoft.EntityFrameworkCore;
return Ok(await _context.User.ToListAsync());
}
///
/// 查询
///
///
///
[HttpGet("{id}")]
public async Task> GetUser(int id)
{
var todoItem = await _context.User.FindAsync(id);
if (todoItem == null)
{
return NotFound();
}
return todoItem;
}
///
/// 添加
///
///
///
[HttpPost]
public async Task> PostUser(User item)
{
_context.User.Add(item);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetUser), new { id = item.Id }, item);
}
///
/// 修改
///
///
///
///
[HttpPut("{id}")]
public async Task PutUser(int id, User item)
{
if (id != item.Id)
{
return BadRequest();
}
_context.Entry(item).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
///
/// 删除
///
///
///
[HttpDelete("{id}")]
public async Task DeleteUser(int id)
{
var todoItem = await _context.User.FindAsync(id);
if (todoItem == null)
{
return NotFound();
}
_context.User.Remove(todoItem);
await _context.SaveChangesAsync();
return NoContent();
}
}
}
现在可以直接运行cor API了
控制台运行方法
打开本地根目录
输入 dotnet run 运行项目
在浏览器输入项目运行地址
运行接口,就可以实时监控运行效果
到此就结束了,
谢谢各位大爷。
成长的道路永远不会一番风顺的,每天成长一点点,加油。
先溜为敬。