循序渐进学.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 一.概述 本篇描述一 ...
随机推荐
- package.json浅谈
相信很多小伙伴都见过各种各样的Node.js项目,而里面都有一个名为package.json的文件,而这个文件究竟是干什么的呢? 简单的来说,这个文件就是对整个项目的各种情况的配置(也是介绍),下面给 ...
- Spring cloud 微服务架构 Eureka篇
1 服务发现 ## 关于服务发现 在微服务架构中,服务发现(Service Discovery)是关键原则之一.手动配置每个客户端或某种形式的约定是很难做的,并且很脆弱.Spring Cloud提供了 ...
- SpringBoot入门Demo(Hello Word Boot)
Spring Boot 是由Pivotal团队提供的全新框架,其设计目的是用来简化新的Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. ...
- Linux命令(一)grep查询
grep -n as test1.txt -n : 显示行号 -v: 显示没有搜索字符的一行 -i:忽视大小写 搜索字符串 模式查找
- [ASP.NET]初试Web API
Web API 1: 需要环境(VS2010/.Net4.0/MVC4 ) http://www.asp.net/web-api/overview/creating-web-apis/creating ...
- OnContextMenu事件(转)
用oncontextmenu事件单禁用右键菜单 一个页面中,BODY中用oncontextmenu='return false'来取消鼠标右键:在JS中设置oncontextmenu='return ...
- org.hibernate.TransientObjectException异常
代码如下: /** * 测试4:新增一个秘书角色,并赋给张三该角色 */ @Test public void test4(){ Session session = HibernateUtils.ope ...
- 云计算--hdfs dfs 命令
在hadoop安装目录下:/hadoop2/hadoop-2.7.3 1.创建目录 bin/hdfs dfs -mkdir /user bin/hdfs dfs -mkdir /user/<us ...
- perl6 HTTP::UserAgent (2)
http://www.cnblogs.com/perl6/p/6911166.html 之前这里有个小小例子, 这里只要是总结一下. HTTP::UserAgent包含了以下模块: --------- ...
- linux远程windows执行命令
Linux下远程连接windows,执行命令 - Feng______的专栏 - 博客频道 - CSDN.NEThttp://blog.csdn.net/feng______/article/deta ...