已被阅读 3199 次 | 文章分类:csharp | 2020-04-25 20:16
说到写restful 接口,估计大部分人都知道java springboot,不过确实也很普及;其实.net webapi创建restful接口同样方便快捷高效,目前推出跨平台的asp.net core框架,所以本节使用netcore+EFcore+Mysql的技术框架搭建一个webapi工程
一:前期准备
假设你是从零开始,那么在开发之前需要准备基础的软件及开发包如下
(1) 编辑器:Visual Studio Code
(2) C# for Visual Studio Code (latest version),在vscode扩展安装即可
(3).NET Core 3.1 SDK or later 开发包
EF Core:
Entity Framework Core,为微软为 .NET Core平台开发的ORM框架。对应是 .NET Framework平台的 Entity Framework(EF),无论是EF还是EF Core都可以说是 .NET 平台开发效率最高的ORM框架
二:开始搭建
1.新建目录
mkdir xiaobai.webapi
2.在根目录下使用CLI命令,新建一个空web工程,文件会以根目录名字命名
dotnet new web
上面两步也可以使用以下命令:
dotnet new web -n xiaobai.web 新建名为xiaobai.web的csproj工程
dotnet new web -o xiaobai.web 会创建一个目录,并生产同名工程
3.EF Core已经集成在 ASP.NET Core 中,但默认并不支持MySQL,如果需要连接MySQL,需要添加MySQL相关的Provider,这里使用一个第三方ORM框架Pomelo.EntityFrameworkCore.MySql 支持链接mysql驱动 ,使用以下命令添加
dotnet add package Pomelo.EntityFrameworkCore.MySql
4.准备一个数据表,可以自己随便建一个,本例使用如下sql创建数据表;也可以直接设计表
// 创建数据库
CREATE DATABASE user
// 创建表
USE user
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`hobby` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5. 在项目根目录appsettings.json写入以下数据库连接配置
准备工作结束,可以写具体核心代码了,先附上一张完成的目录结构
三:核心业务编写
1.创建user表实体类
像mybatis、hibernate、EF、EFCore等ORM框架具体表现便是将一张表映射为一个类,表字段映射为类中的属性,我们可以通过操作实体类,来进行CRUD操作
在根目录新建Models文件夹,在文件夹右键新建cs类,名称为UserEntity,初始内容如下
namespace xiaobai.webapi.Models
{
public class UserEntity
{
}
}
对应数据库的表字段,新建类属性
namespace xiaobai.webapi.Models
{
public class UserEntity
{
public int Id { get; set; }
public int Age { get; set; }
public string Name { get; set; }
public string Hobby { get; set; }
}
}
2.创建数据库上下文,用来实例化数据库表
新建Repositories文件夹,新建xiaobaiDBContext.cs 类;引入三个命名空间,需要用到
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
填写完整后的代码如下:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using xiaobai.webapi.Models;
namespace xiaobai.webapi.Repositories
{
public class xiaobaiDBContext : DbContext
{
private IConfiguration Configuration { get; }
public xiaobaiDBContext(IConfiguration configuration)
{
this.Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBUilder)
{
optionsBUilder.UseMySql(Configuration.GetConnectionString("webapiDB"));
}
public DbSet<UserEntity> Users { get; set; }
}
}
该类继承了 DbContext,然后在Context初始化时配置MySQL,ASP.NET Core 默认使用了DI组件,所以我们取配置文件,就需要在构造函数中获取 IConfiguration 注入的实例,如第一行所示
3.在Startup.cs配置注入,以便数据访问类可以访问DI方式获取xiaobaiDBContext
public void ConfigureServices(IServiceCollection services)
{
//引入MVC模块
services.AddMvc();
//配置DbContext注入
services.AddTransient<xiaobaiDBContext>();
}
4.创建CRUD类,对实体类进行增删改查操作
在Repositories文件夹,新建xiaobaiRepository.cs,填入如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using xiaobai.webapi.Models;
namespace xiaobai.webapi.Repositories
{
public class xiaobaiRepository
{
private xiaobaiDBContext DbContext { get; }
public xiaobaiRepository(xiaobaiDBContext dbcontext)
{
//在构造函数中注入DbContext
this.DbContext = dbcontext;
}
public int Add(UserEntity user)
{
using (DbContext)
{
DbContext.Users.Add(user);
return DbContext.SaveChanges();
}
}
//删除
public int Delete(int id)
{
using (DbContext)
{
var userFromContext = DbContext.Users.FirstOrDefault(u => u.Id == id);
DbContext.Users.Remove(userFromContext);
return DbContext.SaveChanges();
}
}
//更新
public int Update(UserEntity user)
{
using (DbContext)
{
var userFromContext = DbContext.Users.FirstOrDefault(u => u.Id == user.Id);
userFromContext.Name = user.Name;
userFromContext.Age = user.Age;
userFromContext.Hobby = user.Hobby;
return DbContext.SaveChanges();
}
}
//查询
public UserEntity QueryById(int id)
{
using (DbContext)
{
return DbContext.Users.FirstOrDefault(u => u.Id == id);
}
}
//查询集合
public List<UserEntity> QueryByAge(int age)
{
using (DbContext)
{
return DbContext.Users.Where(u => u.Age == age).ToList();
}
}
//查看指定列
public List<string> QueryNameByAge(int age)
{
using (DbContext)
{
return DbContext.Users.Where(u => u.Age == age).Select(u => u.Name).ToList();
}
}
//分页查询
public List<UserEntity> QueryUserPaging(int pageSize, int page)
{
using (DbContext)
{
return DbContext.Users.Skip(pageSize * (page - 1)).Take(pageSize).ToList();
}
}
}
}
5.创建Controllers文件夹,创建UserController.cs ,测试我们的方法
using System;
using xiaobai.webapi.Models;
using xiaobai.webapi.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace xiaobai.webapi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
public xiaobaiRepository Repository { get; }
public UserController(xiaobaiRepository repository)
{
this.Repository = repository;
}
[HttpGet("{id}")]
public UserEntity QueryById(int id)
{
var user = Repository.QueryById(id);
return user;
}
}
}
QQ:3410192267 | 技术支持 微信:popstarqqsmall
Copyright ©2017 xiaobaigis.com . 版权所有 鲁ICP备17027716号