zoukankan      html  css  js  c++  java
  • asp.net core 系列之webapi集成EFCore的简单操作教程

    因为官网asp.net core webapi教程部分,给出的是使用内存中的数据即 UseInMemoryDatabase 的方式,

    这里记录一下,使用SQL Server数据库的方式即 UseSqlServer 的方式。

    环境说明:

    这里使用的是win 7 下的 virtual studio 2017 ,数据库使用的Sql Server

    1.创建一个web项目

    • 文件->新建->项目
    • 选择 ASP.NET Core Web 应用 的模板,项目名 WebApiDemo
    • 在新的 ASP.NET Core Web 应用的页面,选择 API 模板,并确定,不要选择支持Docker

     

    2.增加一个实体类

    • 右击项目,新增一个Models文件夹
    • 在Models文件夹下增加一个类(class),TodoItem

    代码如下

    public class TodoItem
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public bool IsComplete { get; set; }
        }

    3.增加一个数据库上下文实体(database context)

    • 右键Models文件夹,增加一个类,命名 TodoContext

    代码如下

     public class TodoContext : DbContext
        {
            public TodoContext(DbContextOptions<TodoContext> options)
                : base(options)
            {
            }
    
            public DbSet<TodoItem> TodoItems { get; set; }
        }

    4.注册数据库上下文实体

    在 ASP.NET Core 中 ,服务(service)例如 数据库上下文(the DB context),必须被注册到 DI 容器中;

    容器可以给Controller 提供 服务 (service).

    StartUp.cs代码如下

     public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<TodoContext>(opt =>
                opt.UseSqlServer(Configuration.GetConnectionString("DemoContext")));  //使用SqlServer数据库
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
    
    
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
                app.UseMvc();
            }
        }

    注意,这里是不同于官网教程中的地方,对比如下

    ConfigureService方法中:

    //官网
    services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
    //本教程 services.AddDbContext
    <TodoContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DemoContext")));
    Configuration.GetConnectionString("DemoContext") 取得是 appsettings.json 文件中的 字符串,如下
    appsettings.json 内容:
    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*",
      "ConnectionStrings": {
        "TodoContext": "Server=(localdb)\mssqllocaldb;Database=WebApiDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    }

    5.增加初始化迁移,更新数据库

    此步骤,主要是使用code first 方式,在数据库中,创建相应的数据库和实体对应的表

    对应 appsettings.json 文件中的连接字符串 :数据库名 WebApiDemo

    • 工具-> NuGet 包管理器 -> 程序包管理器控制台

    控制台如下:

    命令如下:

    Add-Migration Initial
    Update-Database

    注意,这里要求 power shell 版本 需要是3.0及以上,如果版本不够,可以自己百度然后升级power shell,这里不再详述

    6.增加 Controller 控制器

    • 右键 Controllers 文件夹
    • 添加->控制器
    • 选择 空 API 控制器,命名 TodoController ,添加

    代码如下:

    [Route("api/[controller]")]
        [ApiController]
        public class TodoController : ControllerBase
        {
            private readonly TodoContext _context;
    
            public TodoController(TodoContext context)
            {
                _context = context;
    
                if (_context.TodoItems.Count() == 0)
                {
                    // Create a new TodoItem if collection is empty,
                    // which means you can't delete all TodoItems.
                    _context.TodoItems.Add(new TodoItem { Name = "Item1" });
                    _context.SaveChanges();
                }
            }
    
            // GET: api/Todo
            [HttpGet]
            public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
            {
                return await _context.TodoItems.ToListAsync();
            }
    
            // GET: api/Todo/5
            [HttpGet("{id}")]
            public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
            {
                var todoItem = await _context.TodoItems.FindAsync(id);
    
                if (todoItem == null)
                {
                    return NotFound();
                }
    
                return todoItem;
            }
        }

    这里面有两个方法,主要是为了检验是否成功创建此webapi项目

    7.运行,输入浏览器地址检验

    https://localhost:44385/api/todo

    这里用户根据自己的地址替换即可

    这里作简单记录,方便自己日后查看,如有错误,欢迎指正

    参考网址:

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model?view=aspnetcore-2.2&tabs=visual-studio

     
  • 相关阅读:
    C#零相位数字滤波器,改写自Matlab函数filtfilt
    [收藏]C语言格式化字符串
    C#调用PMAC运动控制卡的pcomm32动态链接库的数据类型转换
    [收藏]常见逻辑电平标准
    主要软件作品展示
    新一年希望做的事情
    单元测试的思维导图
    SQLite简单教程
    关于动态执行SQL Statement on ISeries
    突然发现一个 IBM.Data.DB2.ISeries的一个小问题,也是很头痛的问题
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/10777664.html
Copyright © 2011-2022 走看看