循序渐进学.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 一.概述 本篇描述一 ...
随机推荐
- dwr框架介绍
转: [DWR框架]过时了吗? 置顶 2018年06月02日 11:59:02 许你笑颜 阅读数:4129 版权声明: https://blog.csdn.net/smileyan9/articl ...
- php编程——验证码的实现(session方法)
index.PHP(实现输入验证码页面)代码如下: <html><head><title>check code</title></head> ...
- node.js原生后台进阶(二)
上一章讲到怎么样用原生node.js来获取GET.POST(urlencoded,formData)的参数,这一次我们更进一步,讲一下以下的点: 1.压缩(zlib) 2.流(stream) 3.路由 ...
- Intellij IDEA导入web项目详解(解决访问的404)
开始时的首页 点击modules 点击modules界面的Paths 点击Libraries 选择lib文件 点击Facets 选择项目 这就是我404的主要原因,因为小白第一次使用idea 所以很疯 ...
- linux下编译make文件报错“/bin/bash^M: 坏的解释器,使用grep快速定位代码位置
一.linux下编译make文件报错“/bin/bash^M: 坏的解释器 参考文章:http://blog.csdn.net/liuqiyao_01/article/details/41542101 ...
- Kafka 温故(四):Kafka的安装
Step 1: 下载Kafka > tar -xzf kafka_2.9.2-0.8.1.1.tgz> cd kafka_2.9.2-0.8.1.1 Step 2: 启动服务Kafka用到 ...
- PHP复制文件夹及文件夹内的文件
//1.取被复制的文件夹的名字://2.写出新的文件夹的名字://3.调用此函数,将旧.新文件夹名字作为参数传递://4.如需复制文件夹内的文件,第三个参数传1,否则传0: public functi ...
- [python]使用python实现Hadoop MapReduce程序:计算一组数据的均值和方差
这是参照<机器学习实战>中第15章“大数据与MapReduce”的内容,因为作者写作时hadoop版本和现在的版本相差很大,所以在Hadoop上运行python写的MapReduce程序时 ...
- SANS社区帐号邮件激活问题
注册时,密码需要数字,大写字母,小写字母,符号10位以上才能注册成功 吐槽:谁来爆破一下这种强度的密码,哈哈. 在我的文章中,有 计算机取证 分类,里面的一篇文章 Virtual Worksta ...
- 004_on-my-zsh漂亮的shell
一. http://www.cnblogs.com/GarveyCalvin/p/4301235.html 二. 前言:Zsh可配置性强,用户可以自定义配置,个性化强.Zsh tab补全更强大,该功能 ...