.Net Core 的WebApi项目使用mysql的EF CodeFirst模式

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS MySQL,高可用系列 2核4GB
简介: .Net Core 的WebApi项目使用mysql的EF CodeFirst模式

注.建立.net core的webapi项目参看:


http://blog.csdn.net/zzzili/article/details/75307308



1.需要引用的库有


2021051915414488.png


或者


20210519155040951.png


2.在项目中添加MyDBContext类和实体类User

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataCore
{
    public class User
    {
        public int id { set; get; }        
        public string remark1 { set; get; }
        public string name { set; get; }
        public int age { set; get; }
        public string remark2 { set; get; }
        public DateTime updateTime { set; get; }
        public DateTime createTime { set; get; }
        public bool isEnable { set; get; }        
    }
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
    public class MyDBContext : DbContext
    {
        public MyDBContext(DbContextOptions<MyDBContext> options)
         : base(options)
        {
        }
        public DbSet<User> User { get; set; }
    }
}

3.在Startup类中的ConfigureServices方法添加如下代码:

        public void ConfigureServices(IServiceCollection services)
        {
            // Replace with your connection string.
            var connectionString= Configuration["ConnectionStrings:DefaultConnection"];
            //Pomelo时这样写
            var serverVersion = new MySqlServerVersion(new Version(5, 6, 22));
            services.AddDbContext<MyDBContext>(options =>options.UseMySql(connectionString,serverVersion));
            //或者用mysql ef core时这样写
           services.AddDbContext<MyDBContext>(options =>options.UseMySQL(connectionString));
            services.AddControllers();
        }

appsetting.json中添加:

"ConnectionStrings": {
    "DefaultConnection": "server=localhost;user id=root;pwd=root;database=testcore;"
  },

*******************************************************************************另一种写法,可以在使用MyDBContext时,直接new

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
    public class MyDBContext : DbContext
    {
        public static string connectionString = null;
        public MyDBContext()
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySQL(connectionString);
        }
        public DbSet<User> User { get; set; }
    }
}
//Startup中这样配置,把连接字符串赋值给MyDBContext的静态变量        
public void ConfigureServices(IServiceCollection services)
        {
            // Replace with your connection string.
            var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
            MyDBContext.connectionString = connectionString;            
            services.AddControllers();
        }

*******************************************************************************************

4.控制台内执行


Add-Migration xxx  


Update-Database



5.使用swagger


添加引用:Swashbuckle.AspNetCore

       public void ConfigureServices(IServiceCollection services)
        {
            //使用mysql
            var connectionString= Configuration["ConnectionStrings:DefaultConnection"];
            var serverVersion = new MySqlServerVersion(new Version(5, 6, 22));
            services.AddDbContext<MyDBContext>(options =>
            options.UseMySql(connectionString,serverVersion));
            //Init Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            });
            services.AddControllers();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //InitSwagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v1/swagger.json", "My API V1");
            });
            app.UseMvc();
        }

6.TestController

using DataCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3.Controllers
{
    public class TestInput
    {
        public string str1 { set; get; }
        public string str2 { set; get; }
    }
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpPost]
        public string test2(TestInput input)
        {
            return input.str1+input.str2;
        }
        private readonly MyDBContext dbContext = new MyDBContext();
       [HttpGet]
        public object testmysql()
        {
            User u = new User();
            u.remark1 = "1";
            u.createTime = DateTime.Now;
            dbContext.User.Add(u);
            dbContext.SaveChanges();
            var list = dbContext.User.ToList();
            return list;
        }
    }
}

7.发布到Linux环境,参考文章:http://blog.csdn.net/zzzili/article/details/79213001


***************************************************************************************************************************************************************************************************


完整文件


MyDBContext.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataCore
{
    public class MyDBContext : DbContext
    {
        public static string connectionString = null;
        public MyDBContext()
        {
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySQL(connectionString);
        }
        public DbSet<User> User { get; set; }
        public DbSet<UserOrder> UserOrder { get; set; }
    }
}

Startup.cs

using DataCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3
{
    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)
        {
            // Replace with your connection string.
            var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
            MyDBContext.connectionString = connectionString;            
            services.AddControllers();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseAuthorization();
            //InitSwagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("v1/swagger.json", "My API V1");
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

TestController.cs

using DataCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication3.Controllers
{
    public class TestInput
    {
        public string str1 { set; get; }
        public string str2 { set; get; }
    }
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpPost]
        public string test2(TestInput input)
        {
            return input.str1+input.str2;
        }
        private readonly MyDBContext dbContext = new MyDBContext();
       [HttpGet]
        public object testmysql()
        {
            UserOrder u = new UserOrder();
            u.userId =1;
            u.orderNo = "11111";
            dbContext.UserOrder.Add(u);
            dbContext.SaveChanges();
            var query = from user in dbContext.User
                        join o in dbContext.UserOrder on
                        u.id equals o.userId
                        select new { user,o};
            var list = query.ToList();
            return list;
        }
    }
}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
10月前
|
开发框架 .NET 开发者
简化 ASP.NET Core 依赖注入(DI)注册-Scrutor
Scrutor 是一个简化 ASP.NET Core 应用程序中依赖注入(DI)注册过程的开源库,支持自动扫描和注册服务。通过简单的配置,开发者可以轻松地从指定程序集中筛选、注册服务,并设置其生命周期,同时支持服务装饰等高级功能。适用于大型项目,提高代码的可维护性和简洁性。仓库地址:&lt;https://github.com/khellang/Scrutor&gt;
233 5
|
9月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
151 14
|
11月前
|
开发框架 .NET 程序员
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
Autofac 是一个轻量级的依赖注入框架,专门为 .NET 应用程序量身定做,它就像是你代码中的 "魔法师",用它来管理对象的生命周期,让你的代码更加模块化、易于测试和维护
402 4
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
|
11月前
|
开发框架 .NET C#
在 ASP.NET Core 中创建 gRPC 客户端和服务器
本文介绍了如何使用 gRPC 框架搭建一个简单的“Hello World”示例。首先创建了一个名为 GrpcDemo 的解决方案,其中包含一个 gRPC 服务端项目 GrpcServer 和一个客户端项目 GrpcClient。服务端通过定义 `greeter.proto` 文件中的服务和消息类型,实现了一个简单的问候服务 `GreeterService`。客户端则通过 gRPC 客户端库连接到服务端并调用其 `SayHello` 方法,展示了 gRPC 在 C# 中的基本使用方法。
214 5
在 ASP.NET Core 中创建 gRPC 客户端和服务器
|
10月前
|
开发框架 算法 中间件
ASP.NET Core 中的速率限制中间件
在ASP.NET Core中,速率限制中间件用于控制客户端请求速率,防止服务器过载并提高安全性。通过`AddRateLimiter`注册服务,并配置不同策略如固定窗口、滑动窗口、令牌桶和并发限制。这些策略可在全局、控制器或动作级别应用,支持自定义响应处理。使用中间件`UseRateLimiter`启用限流功能,并可通过属性禁用特定控制器或动作的限流。这有助于有效保护API免受滥用和过载。 欢迎关注我的公众号:Net分享 (239字符)
193 1
|
10月前
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
239 3
|
12月前
|
开发框架 JavaScript 前端开发
一个适用于 ASP.NET Core 的轻量级插件框架
一个适用于 ASP.NET Core 的轻量级插件框架
171 0
|
开发框架 前端开发 .NET
ASP.NET Core 核心特性学习笔记「下」
ASP.NET Core 核心特性学习笔记「下」
|
开发框架 前端开发 中间件
ASP.NET Core 核心特性学习笔记「上」
ASP.NET Core 核心特性学习笔记「上」
|
移动开发 中间件 .NET
ASP.NET Core 2 学习笔记(三)中间件
原文:ASP.NET Core 2 学习笔记(三)中间件 之前ASP.NET中使用的HTTP Modules及HTTP Handlers,在ASP.NET Core中已不复存在,取而代之的是Middleware。
1052 60

推荐镜像

更多