循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)

摘要:
数据库建表Product,字段名称、类型和实体类字段名称、类型一致:所有实体类的属性在数据库都要有对应字段,但数据库表可以有多余的字段。还有两个问题需要处理一下:1、我们希望在Context中定义的实体DbSet的名称为Products而不是Product,同时希望数据库中对应的表名称为:Base_Product,这样更符合习惯。

系列目录

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

本系列涉及到的源码下载地址:https://github.com/seabluescn/Blog_WebApi

一、概述

本篇讨论如何连接数据库,包括连接SQL Server 和 连接MySQL,然后做一些基本的数据操作。

二、连接SQL Server

首先通过NuGet添加相关的包:

循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)第1张

新建一个实体类:

  public classProduct
    {      
        [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 classSalesContext: DbContext
    {
        public DbSet<Product> Product { get; set; }
        protected override voidOnConfiguring(DbContextOptionsBuilder builder)
        {
            String connStr = "Server=localhost;Database=Sales;User Id=sales;Password=sales2018;";
            builder.UseSqlServer(connStr);
        }
    }

并在Startup中注册服务

public classStartup
    {       
        //This method gets called by the runtime. Use this method to add services to the container.
        public voidConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<SalesContext>();
        }
    }

新建一个Controller,可以进行数据库的操作了

    [Produces("application/json")]  
    [Route("api/products")]
    public classProductsController : Controller
    {
        private readonlySalesContext _context;
        publicProductsController(SalesContext context)
        {
            _context =context;
        }
        /// <summary>
        ///获取产品列表
        /// </summary>
        /// <returns>产品列表</returns>
[HttpGet]
        public List<Product>GetAllProducts()
        {
            List<Product> products = _context.Products.ToList<Product>();
            returnproducts;
        }  
    }

下面把数据库和表建好,对于SQL Server,采用Windows身份认证登陆后,建数据库Sales和用户sales,进行相应权限设置后,确保可以通过SQL Server Management Studio以SQL Server认证的方式登陆数据库并可以进行数据操作。

数据库建表Product,字段名称、类型和实体类字段名称、类型一致:

循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)第2张

所有实体类的属性在数据库都要有对应字段,但数据库表可以有多余的字段。

此时应该就可以通过 http://localhost:5000/api/products来查询数据了。

还有两个问题需要处理一下:

1、我们希望在Context中定义的实体DbSet的名称为Products而不是Product,同时希望数据库中对应的表名称为:Base_Product,这样更符合习惯。

 public classSalesContext: DbContext
    {
        public DbSet<Product> Products { get; set; }       
        protected override voidOnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().ToTable("Base_Product");
        }
    }

2、我们的数据类连接字符串写在代码里了,需要把它移到配置文件里。

首先清空或删除DbContext类OnConfiguring的方法

 protected override voidOnConfiguring(DbContextOptionsBuilder builder)
        {
           
        }

改为在Startup中读取配置文件

        public voidConfigureServices(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、增加包引用:

循序渐进学.Net Core Web Api开发系列【8】:访问数据库(基本功能)第3张

2、修改服务注册代码如下

public voidConfigureServices(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 classProductsController : Controller
    {
        private readonlySalesContext _context;
        publicProductsController(SalesContext context)
        {
            _context =context;
        }
        /// <summary>
        ///获取产品列表
        /// </summary>
        /// <returns>产品列表</returns>
[HttpGet]
        public List<Product>GetAllProducts()
        {
            List<Product> products = _context.Products.ToList<Product>();
            returnproducts;
        }
        /// <summary>
        ///根据产品编号查询产品信息(非模糊查询)
        /// </summary>
        /// <param name="code">产品编码</param>
        /// <returns>产品信息</returns>
        [HttpGet("{code}")]  
        publicProduct GetProductByCode(String code)
        {
            Console.WriteLine($"GetProductByCode:code={code}");
            Product product =_context.Products.Find(code);
            returnproduct;
        }   
        /// <summary>
        ///新增产品
        /// </summary>
        /// <param name="product">产品信息</param>
[HttpPost]
        public stringAddProduct([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(stringcode)
        {
            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 voidUpdate(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】:访问数据库(基本功能)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Weblogic安装与配置图文详解jquery应用图片拖拽排序下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

vue 调用本地json配置

在webpack.dev.conf.js文件中 /*----------------jsonServer---------*/ /*引入json-server*/const jsonServer = require('json-server') /*搭建一个server*/const apiServer =jsonServer.create() /*将d...

ios图片添加文字或者水印

  在项目中,我们会对图片做一些处理,但是我们要记住,一般在客户端做图片处理的数量不宜太多,因为受设备性能的限制,如果批量的处理图片,将会带来交互体验性上的一些问题。首先让我们来看看在图片上添加文字的方法、    -(UIImage *)addText:(UIImage *)img text:(NSString *)text1{ //上下文的大小 int...

iOS 设置图片imageView圆角——对图片进行裁剪

以前设置图片圆角总是把imageView设置成圆形,然后设置maskToBounds为YES,其实这样处理很消耗性能,图片多了之后比较卡,最好将图片进行裁剪后显示;这里有个分类可以用: UIImage+wiRoundedRectImage.h #import <UIKit/UIKit.h> @interface UIImage (wiR...

基于python的种子搜索网站-开发过程

本讲会对种子搜索网站的开发过程进行详细的讲解。 源码地址:https://github.com/geeeeeeeek/bt 项目开发过程 项目简介 该项目是基于python的web类库django开发的一套web网站,做为本人的毕业设计。本人的研究方向是一项关于搜索的研究项目。在该项目中,笔者开发了一个简单版的搜索网站,实现了对数据库数据的检索和更新。 网...

.net core api +swagger(一个简单的入门demo 使用codefirst+mysql)

前言: 自从.net core问世之后,就一直想了解。但是由于比较懒惰只是断断续续了解一点。近段时间工作不是太忙碌,所以偷闲写下自己学习过程。慢慢了解.net core 等这些基础方面学会之后再用.net core写一个项目,前期文章都是为之后的项目做准备。同时也希望这些基础文章能帮助更多的想入手 .net core的小白。(文中如有不正确地方欢迎各位指正...

HTTP OPTIONS跨域请求

一、场景 今天在监测跨域代码时发现,在调用后端接口的时候会出现两次请求:OPTIONS请求和POST请求。代码如下: /// <summary> /// 自定义中间件要执行的逻辑 /// </summary> /// <param name="context"></param> /// <returns...