系列目录

循序渐进学.Net Core Web Api开发系列目录

本系列涉及到的源码下载地址: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】:访问数据库(基本功能)的更多相关文章

  1. 循序渐进学.Net Core Web Api开发系列【0】:序言与目录

    一.序言 我大约在2003年时候开始接触到.NET,最初在.NET framework 1.1版本下写过代码,曾经做过WinForm和ASP.NET开发.大约在2010年的时候转型JAVA环境,这么多 ...

  2. 循序渐进学.Net Core Web Api开发系列【16】:应用安全续-加密与解密

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 应用安全除 ...

  3. 循序渐进学.Net Core Web Api开发系列【15】:应用安全

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍W ...

  4. 循序渐进学.Net Core Web Api开发系列【14】:异常处理

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍异 ...

  5. 循序渐进学.Net Core Web Api开发系列【13】:中间件(Middleware)

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  6. 循序渐进学.Net Core Web Api开发系列【12】:缓存

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  7. 循序渐进学.Net Core Web Api开发系列【11】:依赖注入

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇介绍如 ...

  8. 循序渐进学.Net Core Web Api开发系列【10】:使用日志

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.本篇概述 本篇介 ...

  9. 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作

    系列目录 循序渐进学.Net Core Web Api开发系列目录 本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi 一.概述 本篇描述一 ...

随机推荐

  1. 个推用户画像产品(个像)iOS集成实践

    最近业务方给我们部门提了新的需求,希望能构建精准用户画像.我们尝试使用的是个推(之前专门做消息推送的公司)旗下新推出的产品“个像·用户画像”.根据官方的说法,个像能够为APP开发者提供丰富的用户画像数 ...

  2. kubespray 一键安装k8s集群

    1. clone代码 git clone https://github.com/kubernetes-incubator/kubespray.git 2. 添加inventory/inventory ...

  3. 使用easyui实现双击列表中某个值直接对其进行修改

    var editCell = undefined; $('#dg').datagrid({ url:'DwzServlet', iconCls:'icon icon-list' , queryPara ...

  4. Linux-Xshell会话保持

    1.Xshell客户端设置 2.服务端设置 修改/etc/ssh/sshd_config文件,找到 ClientAliveInterval 0和ClientAliveCountMax 3并将注释符号( ...

  5. 关于System.getProperty("java.io.tmpdir");的输出,及System.getProperty();参数

    1,首先来介绍下System.getProperty("java.io.tmpdir")输出因为这个输出有点特殊. 理论介绍:他是获取系统临时目录.可以是window的temp,l ...

  6. bash脚本:集群资源争夺战crazy-killer

    背景 公司的集群很多人一起用,有时候就难免资源紧张,某次需要用的时候没资源等了半天还是没资源,再等半天还是没资源,于是就写了个脚本泄愤,建议看到的人拷走放在自己公司集群上长期运行 :) 实现 此脚本运 ...

  7. [uart]1.Linux中tty框架与uart框架之间的调用关系剖析

    转自:http://developer.51cto.com/art/201209/357501_all.htm 目录 1.tty框架 2.uart框架 3.自底向上 4.自顶向下 5.关系图 在这期间 ...

  8. 查看nginx | apache | php | tengine | tomcat版本的信息以及如何隐藏版本信息【转】

    转自: 查看nginx | apache | php | tengine | tomcat版本的信息以及如何隐藏版本信息 - 追马 - 51CTO技术博客http://lovelace.blog.51 ...

  9. MySQL一问一答

    一.问:如果有一张表,里面有个字段为id的自增主键,当已经向表里面插入了10条数据之后,删除了id为8,9,10的数据,再把mysql重启,之后再插入一条数据,那么这条数据的id值应该是多少,是8,还 ...

  10. vue组件库(一):前期准备工作

    前言 将近期项目内自行开发一个vue组件,做个总结,记录下自己的思维过程~~~ 正文 接到这个任务后,还是要做些准备工作的. 主要内容如下: 1.优化下所在团队前端开发流程 服务器搭建gitlab,采 ...