• 入坑.net core(三).net core api 3.1 反向工程 增删改查


    话接上回:入坑.net core (二) swagger 配置

    有兴趣的可以看一下,废话不多少,

    接下来 教大家怎么用.net core 配置数据库,实现增删改查

    1.点开VS扩展-》管理扩展

     搜索 EF

    安装EF Core Power Tools工具

    在这里需要关闭VS工具,安装好再打开当前项目

    2.右击项目 点击EF Core 工具 选择反向工程

     

    选择版本,对应当前项目 我的是3.0 

    选择表,全选

    配置实体和上下文,我这新建了Model类库,可以自行配置

    配置好点确定

     提示:没有找到Microsoft.EntityFrameworkCore库

    管理NuGet程序包,配置

    再配置以下库

    (1)Microsoft.EntityFrameworkCore.SqlServer(连接sql server数据库的包)

    (2)Microsoft.EntityFrameworkCore.Tools(命令行所需的库)

    (3)Microsoft.EntityFrameworkCore.Design(vs code命令行所需的库,vs2019,不需要安装)

    安装版本一定要看仔细

    接着配置appsettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Information",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "SQLServerConnection": "Data Source=.;Initial Catalog=vuetest;Integrated Security=True"
    
      }
    }

    配置:Startup.cs

                //连接sqlserver
                services.AddDbContext<vuetestContext>(options =>
                {
                    options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection"));
    
                });

     

    最后我们添加API控制器 放增删改查

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Model;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Web_API.Controllers
    {
        //路由设置
        [Route("api/[controller]")]
        [ApiController]
        public class UserController : ControllerBase
        {
            private readonly vuetestContext _context;
            /// <summary>
            /// 初次判断
            /// </summary>
            /// <param name="context"></param>
            public UserController(vuetestContext context)
            {
                _context = context;
                if (_context.User.Count() == 0)
                {
                    _context.User.Add(new User { UserName = "admin", PassWord = "0837EB79BC250163", UserType = 0, Status = 0, Del = 0 });
                    _context.SaveChanges();
                }
            }
    
            /// <summary>
            /// 异步获取
            /// </summary>
            /// <returns></returns>
            [HttpGet]
    
            public async Task<IActionResult> GetUser()
            {
                //ToListAsync在命名空间 using Microsoft.EntityFrameworkCore;
                return Ok(await _context.User.ToListAsync());
            }
    
            /// <summary>
            /// 查询
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            [HttpGet("{id}")]
            public async Task<ActionResult<User>> GetUser(int id)
            {
                var todoItem = await _context.User.FindAsync(id);
                if (todoItem == null)
                {
                    return NotFound();
                }
                return todoItem;
            }
            /// <summary>
            /// 添加
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            [HttpPost]
            public async Task<ActionResult<User>> PostUser(User item)
            {
                _context.User.Add(item);
                await _context.SaveChangesAsync();
                return CreatedAtAction(nameof(GetUser), new { id = item.Id }, item);
            }
    
            /// <summary>
            /// 修改
            /// </summary>
            /// <param name="id"></param>
            /// <param name="item"></param>
            /// <returns></returns>
            [HttpPut("{id}")]
            public async Task<IActionResult> PutUser(int id, User item)
            {
                if (id != item.Id)
                {
                    return BadRequest();
                }
                _context.Entry(item).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return NoContent();
            }
            /// <summary>
            /// 删除
            /// </summary>
            /// <param name="id"></param>
            /// <returns></returns>
            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteUser(int id)
            {
                var todoItem = await _context.User.FindAsync(id);
                if (todoItem == null)
                {
                    return NotFound();
                }
                _context.User.Remove(todoItem);
                await _context.SaveChangesAsync();
                return NoContent();
            }
        }
    }
    

      

    现在可以直接运行cor API了

    控制台运行方法

    打开本地根目录

     输入 dotnet run 运行项目

    在浏览器输入项目运行地址

    运行接口,就可以实时监控运行效果

     

    到此就结束了,

    谢谢各位大爷。

    成长的道路永远不会一番风顺的,每天成长一点点,加油。

    先溜为敬。

  • 相关阅读:
    CSS 自适应技巧
    实现在线阅读WORD,PDF等文件,JAVA,PHP都可以
    最简单的无线分类,无限树形菜单解决方案
    python生成组织架构图(网络拓扑图、graph.editor拓扑图编辑器)
    python将字符串类型改成日期类型
    python发送邮件
    下载Crypto,CyCrypto,PyCryptodome 报错问题
    UnicodeEncodeError: 'latin-1' codec can't encode characters in position 41-50: ordinal not in range(256)
    pymysql.err.InterfaceError: (0, '')解决办法
    经典三级联动
  • 原文地址:https://www.cnblogs.com/jstblog/p/16293669.html
Copyright © 2020-2023  润新知