循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)
系列目录
本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi
一、概述
本篇讨论如何连接数据库,包括连接SQL Server 和 连接MySQL,然后做一些基本的数据操作。
二、连接SQL Server
首先通过NuGet添加相关的包:

新建一个实体类:
public class Product
{
[Key]
public string Code { get; set; }
public string Name { get; set; }
public string Descript { get; set; }
public int Numbers { get; set; }
}
[Key]特性标识表明Code为主键。
新建一个DBContext类
public class SalesContext: DbContext
{
public DbSet<Product> Product { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
String connStr = "Server=localhost;Database=Sales;User Id=sales;Password=sales2018;";
builder.UseSqlServer(connStr);
}
}
并在Startup中注册服务
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SalesContext>();
}
}
新建一个Controller,可以进行数据库的操作了
[Produces("application/json")]
[Route("api/products")]
public class ProductsController : Controller
{
private readonly SalesContext _context;
public ProductsController(SalesContext context)
{
_context = context;
}
/// <summary>
/// 获取产品列表
/// </summary>
/// <returns>产品列表</returns>
[HttpGet]
public List<Product> GetAllProducts()
{
List<Product> products = _context.Products.ToList<Product>();
return products;
}
}
下面把数据库和表建好, 对于SQL Server,采用Windows身份认证登陆后,建数据库Sales和用户sales,进行相应权限设置后,确保可以通过SQL Server Management Studio以SQL Server认证的方式登陆数据库并可以进行数据操作。
数据库建表Product,字段名称、类型和实体类字段名称、类型一致:

所有实体类的属性在数据库都要有对应字段,但数据库表可以有多余的字段。
此时应该就可以通过 http://localhost:5000/api/products来查询数据了。
还有两个问题需要处理一下:
1、我们希望在Context中定义的实体DbSet的名称为Products而不是Product,同时希望数据库中对应的表名称为:Base_Product,这样更符合习惯。
public class SalesContext: DbContext
{
public DbSet<Product> Products { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("Base_Product");
}
}
2、我们的数据类连接字符串写在代码里了,需要把它移到配置文件里。
首先清空或删除DbContext类OnConfiguring的方法
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{ }
改为在Startup中读取配置文件
public void ConfigureServices(IServiceCollection services)
{
String connStr = Configuration.GetConnectionString("SQLServerConnection");
services.AddDbContext<SalesContext>(builder=> builder.UseSqlServer(connStr));
}
配置文件applicatios.json内容如下:
{
"ConnectionStrings": {
"SQLServerConnection": "Server=localhost;Database=Sales;User Id=sales;Password=sales2018;"
}
}
三、连接MySQL
1、增加包引用:

2、修改服务注册代码如下
public void ConfigureServices(IServiceCollection services)
{
String connStr = Configuration.GetConnectionString("MySQLConnection");
services.AddDbContext<SalesContext>(builder=> builder.UseMySQL(connStr));
}
配置文件信息如下:
{"MySQLConnection":"Server=58.220.197.198;port=3317;database=sales;uid=sales;pwd=sales;SslMode=None;"
}
因为默认采用SSL连接模式,如果数据库没有提供,需要增加SslMode=None
四、一些基本操作
/// <summary>
/// 产品信息接口
/// </summary>
[Produces("application/json")]
[Route("api/products")]
public class ProductsController : Controller
{
private readonly SalesContext _context; public ProductsController(SalesContext context)
{
_context = context;
} /// <summary>
/// 获取产品列表
/// </summary>
/// <returns>产品列表</returns>
[HttpGet]
public List<Product> GetAllProducts()
{
List<Product> products = _context.Products.ToList<Product>();
return products;
} /// <summary>
/// 根据产品编号查询产品信息(非模糊查询)
/// </summary>
/// <param name="code">产品编码</param>
/// <returns>产品信息</returns>
[HttpGet("{code}")]
public Product GetProductByCode(String code)
{
Console.WriteLine($"GetProductByCode:code={code}");
Product product = _context.Products.Find(code);
return product;
} /// <summary>
/// 新增产品
/// </summary>
/// <param name="product">产品信息</param>
[HttpPost]
public string AddProduct([FromBody]Product product)
{
if(product==null)
{
Console.WriteLine("Add product : null");
return null;
} Console.WriteLine($"Add product :{product.Name}");
_context.Products.Add(product);
_context.SaveChanges(); return "success";
} /// <summary>
/// 删除产品
/// </summary>
/// <param name="code">编码</param>
[HttpDelete("{code}")]
public void Delete(string code)
{
Console.WriteLine($"Delete product: code={code}");
Product product = _context.Products.Find(code);
if (product != null)
{
_context.Products.Remove(product);
_context.SaveChanges();
} return;
} /// <summary>
/// 更新产品信息
/// </summary>
/// <param name="code">产品编码</param>
/// <param name="newproduct">产品信息</param>
[HttpPut("{code}")]
public void Update(String code, [FromBody]Product newproduct)
{
Console.WriteLine($"Change product ({code}):Name={newproduct.Name}");
Product product = _context.Products.Find(code);
product.Name = newproduct.Name; _context.SaveChanges();
return;
}
}
五、关于CodeFirst和DBfirst
很多教程都提到CodeFirst和DBfirst的操作,但我在实际使用中没有碰到这个应用场景,正常项目的研发一般都是建一些表写一些代码,再建一些表写一些代码,以此类推,很少有项目是真正把表全部建完再写代码的吧。
循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)的更多相关文章
- 循序渐进学.Net Core Web Api开发系列【0】:序言与目录
一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...
- 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...
- 循序渐进学.Net Core Web Api开发系列【15】:应用安全
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...
- 循序渐进学.Net Core Web Api开发系列【14】:异常处理
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...
- 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...
- 循序渐进学.Net Core Web Api开发系列【12】:缓存
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...
- 循序渐进学.Net Core Web Api开发系列【11】:依赖注入
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...
- 循序渐进学.Net Core Web Api开发系列【10】:使用日志
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇介 ...
- 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作
系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...
随机推荐
- RabbitMQ入门介绍
1.关于AMQP协议 AMQP,即Advanced Message Queuing Protocol,一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设 ...
- 原始套接字-自定义IP首部和TCP首部
/* ===================================================================================== * * Filenam ...
- meeting,symposium,seminar 等区别
meeting,symposium,seminar 等区别 会议分类的方式可说是不胜枚举,这点初步由英文对会议名称的写法,就可看出端倪,像是Assembly,Caucus,Colloquium, Co ...
- Linux iptables常用命令的使用
为什么会有本文 因为最近帮一个朋友布署一个上网梯子,他那边本来用的是v2ray,但是他想用ssr,但是安装配置ssr过程中出了很多问题,比如linux内核版本4.9有点老,不支持bbr加速.无法连接s ...
- cordova app 监听物理返回键
物理返回键指的是手机系统自带的返回按钮,通过cordova监听返回按钮操作,可以禁止某些页面的返回操作,以及实现点击两次返回按钮退出应用. var pageUrl = window.location. ...
- 通过JavaScript自由切换iframe
我发现我有很大的强迫症,如果看到别人的文章没有最终的效果图,我会毫不犹豫关掉这个页面.真的很炸毛这种,让我有很不舒服的体验:所以纵使网上有类似的了,我还是写一篇给那些跟我有同样症状的人阅读. 首先来学 ...
- VS2017创建类库项目后添加不了WPF资源字典
第一步: 先找到你需要添加的库类工程文件,位置如下: 第二步: 使用记事本文件打开,找到图片的位置,把三行代码粘贴进去,保存文件.重新打开项目: 三行代码如下: <ProjectTypeGuid ...
- 大数据系列之数据仓库Hive命令使用及JDBC连接
Hive系列博文,持续更新~~~ 大数据系列之数据仓库Hive原理 大数据系列之数据仓库Hive安装 大数据系列之数据仓库Hive中分区Partition如何使用 大数据系列之数据仓库Hive命令使用 ...
- springcloud微服务架构搭建:服务调用
spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign. Ribbon是一个基于HTTP和TCP客户端的负载均衡器,类似nginx反向代理,可 ...
- 设置adb server的端口号
在操作系统的系统环境里面,加一个环境变量: ANDROID_ADB_SERVER_PORT,值为9999,看自己喜欢.