循序渐进学.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 一.概述 本篇描述一 ...
随机推荐
- ubuntu ssh root登陆
原文:https://blog.csdn.net/wy_97/article/details/78294562 1.默认使用ubuntu用户登录,密码为服务器配置时设置的密码,可在重置密码中修改 2. ...
- C#_界面程序_数码游戏
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 《Linux命令行与shell脚本编程大全》第十一章 构建基本脚本
11.1使用多个命令 $date;who // 命令列表,加入分号就可以,这样会依次执行.参见5.2.1节 注意区分$(date;who),这个是进程列表,会生成一个子shell来执行 Shel ...
- [转载]TypeScript 入门指南
之前有听过,但未使用过,而最近在用nodejs,angularjs做一些前端项目,想到了这个来,正是学习TypeScript的时候,看介绍貌似和coffeescript相似,也JavaScript的转 ...
- J2EE规范 - 13种规范
J2EE是由SUN提出的用于简化开发企业级应用程序的一系列规范的组合,J2EE基于中间层集成的框架的方式为应用开发提供了一个统一的开发平台.基于容器管理.组件化的模型为企业建立一个高可用性,高可靠性可 ...
- java学习第05天(数组常见操作、数组中的数组)
(4)数组常见操作 a.遍历取值 class ArrayDemo3 { public static void main(String[] args) { //System.out.println(&q ...
- Linux 网络操作
Linux 基础网路操作 ifconfig eth0 down # 禁用网卡 ifconfig eth0 up # 启用网卡 ifup eth0: # 启用网卡 mii-tool em1 # 查看网 ...
- ftp 服务
ftp 上传下载 yum install ftp -y ftp:192.168.1.1 上传 put file1 下载 get file2 直接方式 ftp get test.tar.gz 文件 ft ...
- Ascending Rating(单调队列)
题目描述 Before the start of contest, there are n ICPC contestants waiting in a long queue. They are lab ...
- 02 workerman之GatewayWorker简单的demo 实现两端发送消息
前端代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <t ...