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

本文涉及的产品
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
简介: .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;
相关文章
|
6月前
|
SQL Oracle 关系型数据库
MySQL的sql_mode模式说明及设置
MySQL的sql_mode模式说明及设置
967 112
|
9月前
|
Java 关系型数据库 MySQL
在Linux平台上进行JDK、Tomcat、MySQL的安装并部署后端项目
现在,你可以通过访问http://Your_IP:Tomcat_Port/Your_Project访问你的项目了。如果一切顺利,你将看到那绚烂的胜利之光照耀在你的项目之上!
480 41
|
9月前
|
存储 关系型数据库 MySQL
【赵渝强老师】OceanBase数据库从零开始:MySQL模式
《OceanBase数据库从零开始:MySQL模式》是一门包含11章的课程,涵盖OceanBase分布式数据库的核心内容。从体系架构、安装部署到租户管理、用户安全,再到数据库对象操作、事务与锁机制,以及应用程序开发、备份恢复、数据迁移等方面进行详细讲解。此外,还涉及连接路由管理和监控诊断等高级主题,帮助学员全面掌握OceanBase数据库的使用与管理。
495 5
|
人工智能 JavaScript 关系型数据库
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
467 14
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
|
开发框架 前端开发 .NET
一个适用于 .NET 的开源整洁架构项目模板
一个适用于 .NET 的开源整洁架构项目模板
278 26
|
开发框架 安全 .NET
【Azure Developer】.NET Aspire 项目本地调试遇 Grpc.Core.RpcException 异常( Error starting gRPC call ... )
Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
384 12
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
264 14
|
NoSQL Java 关系型数据库
Liunx部署java项目Tomcat、Redis、Mysql教程
本文详细介绍了如何在 Linux 服务器上安装和配置 Tomcat、MySQL 和 Redis,并部署 Java 项目。通过这些步骤,您可以搭建一个高效稳定的 Java 应用运行环境。希望本文能为您在实际操作中提供有价值的参考。
862 26
|
开发框架 .NET 程序员
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
Autofac 是一个轻量级的依赖注入框架,专门为 .NET 应用程序量身定做,它就像是你代码中的 "魔法师",用它来管理对象的生命周期,让你的代码更加模块化、易于测试和维护
596 4
驾驭Autofac,ASP.NET WebApi实现依赖注入详细步骤总结
|
12月前
|
传感器 人工智能 机器人
D1net阅闻|OpenAI机器人项目招新 或自研传感器
D1net阅闻|OpenAI机器人项目招新 或自研传感器

推荐镜像

更多