新建.net core webapi项目

在NuGet包管理器中搜索 MySql.Data.EntityFrameworkCore并安装,安装的8.0.14版本,只安装这一个就够了

安装后创建DataContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; namespace WebApplication4
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{ } public DbSet<TbUser> tbusers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TbUser>();
}
}
}

TbUser.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks; namespace WebApplication4
{
public class TbUser
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public string NickName { get; set; }
public string Email { get; set; }
}
}

appsettings.json中添加连接字符串

{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"dbconn": "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=cnis;SslMode=none"
},
"AllowedHosts": "*"
}

Startup.cs中注入DbContext

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options => options.UseMySQL(Configuration.GetConnectionString("dbconn")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

在Configure方法后面添加DataContext context参数,添加context.Database.EnsureCreated();这样程序运行时,库表不存在的话,会自动创建,不然会报数据库不存在的错误,不用担心DataContext context的传参,该参数会被.net core框架自动注入

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataContext context)
{
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(); context.Database.EnsureCreated();
}

添加UserController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace WebApplication4.Controllers
{ [Produces("application/json")]
[Route("api/user")]
public class UserController: ControllerBase
{
private readonly DataContext _context; public UserController(DataContext context)
{
this._context = context;
} // POST api/user
[HttpPost]
public int Post(TbUser user)
{
_context.Add(user); _context.SaveChanges(); return ;
} // GET api/user
[HttpGet]
public List<TbUser> Get()
{
_context.Database.EnsureCreated();
var users = _context.tbusers;
List<TbUser> items = new List<TbUser>();
foreach (var item in users)
{
items.Add(item);
}
return items;
} // GET api/user/5
[HttpGet("{id}")]
public TbUser Get(int id)
{
var u = _context.tbusers.Find(id);
return u;
} // DELETE api/user/5
[HttpDelete("{id}")]
public int Delete(int id)
{
var u = _context.tbusers.Remove(new TbUser() { ID = id });
_context.SaveChanges();
return ;
} // PUT api/user/5
[HttpPut("{id}")]
public int Put(int id, TbUser user)
{
var u = _context.tbusers.Update(user);
_context.SaveChanges();
return ;
}
}
}

这时运行程序访问系统,就会自动创建库和表,如果需要做数据库迁移,则执行如下命令:

如果用的是vs code,则在终端中执行

dotnet ef migrations add firstMigrations

dotnet ef database update

PS F:\projects\myApi\MyApi> dotnet ef migrations add firstMigrations
info: Microsoft.EntityFrameworkCore.Infrastructure[]
Entity Framework Core 2.2.-servicing- initialized 'DataContext' using provider 'MySql.Data.EntityFrameworkCore' with options: None
Done. To undo this action, use 'ef migrations remove'

PS F:\projects\myApi\MyApi> dotnet ef database update
  Build failed.
  PS F:\projects\myApi\MyApi>

如果用的是vs,在NuGet程序包管理器控制台中执行迁移命令

Add-Migration FirstMigration
Update-Database

首次进行迁移执行update-database的时候,会报错:

MySql.Data.MySqlClient.MySqlException (0x80004005): Table 'test.__efmigrationshistory' doesn't exit

解决方式是:
手动创建这个 'test.__efmigrationshistory' 表

 CREATE TABLE `__EFMigrationsHistory`
(
`MigrationId` nvarchar() NOT NULL,
`ProductVersion` nvarchar() NOT NULL,
PRIMARY KEY(`MigrationId`)
);

然后执行update-database
这样数据迁移就能完成了,表现表已经创建好了,再运行程序

http://localhost:17800/api/user

返回json数据

[{"id":,"nickName":"张三","email":"123@abc.com"}]

.net core使用ef core操作mysql数据库的更多相关文章

  1. 以EF形式操作mysql数据库

    1.引入Nuget包: 2.书写EF操作上下文 public class MySqlContext:DbContext { protected override void OnConfiguring( ...

  2. 在.net core web 项目中操作MySql数据库(非ORM框架,原生sql语句方式)

    本案例通过MySql.Data和Dapper包执行原生sql,实现对数据库的操作. 操作步骤: 第1步:在MySql数据库中新建表User(使用Navicat For MySql工具) 建表语句: c ...

  3. .NET Core Dapper操作mysql数据库

    前言 现在ORM盛行,市面上已经出现了N款不同的ORM套餐了.今天,我们不谈EF,也不聊神马黑马,就说说 Dapper.如何在.NET Core中使用Dapper操作Mysql数据库呢,让我们跟随镜头 ...

  4. ASP.NET Core使用EF Core操作MySql数据库

    ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...

  5. .NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程

    本文首发于<.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程> 前言 在.NET Core/. ...

  6. .net core使用orm操作mysql数据库

    Mysql数据库由于其体积小.速度快.总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库.MySQL是一个多用户.多线程的关系型数据库管理系 ...

  7. net Core 通过 Ef Core 访问、管理Mysql

    net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...

  8. 使用EF操作Mysql数据库中文变问号的解决方案

    问题场景:使用Entity Framework 6.0 操作Mysql数据库,中文保存至数据库后全部变成问号.但是使用Mysql API却不会. 原因排查:首先想到的肯定是数据库编码问题,一次查询了表 ...

  9. ASP.NET CORE 使用 EF CORE访问数据库

    asp.net core通过ef core来访问数据库,这里用的是代码优先,通过迁移来同步数据库与模型. 环境:vs2017,win10,asp.net core 2.1 一.从建立asp.net c ...

  10. Dapper操作MySQL数据库获取JSON数据中文乱码

    前言 在项目中利用Dapper将JSON数据存储到MySQL数据库,结果发现JSON数据中的中文乱码,特此记录,希望对存储JSON的童鞋能有所帮助,文中若有错误之处,还望批评指正. Dapper获取J ...

随机推荐

  1. ubuntu 14.04 pytorch安装

    一. pytorch官网上有安装说明: 但是在安装过程中,由于pip版本为1.5.4,需要先对pip版本进行升级才行,升级步骤如下: 1. sudo apt-get remove python-pip ...

  2. Atitit s2018.2 s2 doc list on home ntpc.docx  \Atiitt uke制度体系 法律 法规 规章 条例 国王诏书.docx \Atiitt 手写文字识别 讯飞科大 语音云.docx \Atitit 代码托管与虚拟主机.docx \Atitit 企业文化 每日心灵 鸡汤 值班 发布.docx \Atitit 几大研发体系对比 Stage-Gat

    Atitit s2018.2 s2 doc list on home ntpc.docx \Atiitt uke制度体系  法律 法规 规章 条例 国王诏书.docx \Atiitt 手写文字识别   ...

  3. Linux系统查毒软件ClamAV (online)

    ClamAV是一个可用于Linux平台上的开源杀毒引擎,可检测木马.病毒.恶意软件和其他恶意的威胁. 官网:http://www.clamav.net/ 一.CentOS环境安装 # yum inst ...

  4. vue及ElementUI环境搭建

    1. nodejs安装及npm安装 下载地址:https://nodejs.org/en/download/ 选择windows Installer 下载完成后 运行node-v8.11.1-x64. ...

  5. xml序列化与反序列化工具

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  6. Excel公式笔记

    跨表,查找相同的数据,的其他列的值 =index(sheet2!$c$:$c$,match(sheet1!$b$,sheet2!$d$:$d$,)) 备注: =index(读哪里的数据(大范围), m ...

  7. jenkins GitHub 自动触发

    jenkins GitHub 自动触发 转载请注明出处: 转载自Bin's Blog:  jenkins GitHub 自动触发( http://www.wenbin.cf/post/54/ ) 需要 ...

  8. Zookeeper客户端介绍

    客户端是开发人员使用Zookeeper的主要的途径,以下内容将对Zookeeper的内部原理进行详细的学习和讲解.ZooKeeper的客户端主要有一下几个核心组件组成: Zookeeper:提供客户端 ...

  9. C语言 goto语句

    /* goto语句 */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* goto语句也 ...

  10. Houdini技术体系 基础管线(二) :Heightfiled与UE4的无缝导入以及对World Composition的支持

    Authored by TraceYang 前言    传统的制作做比较真实大世界3D关卡地形时,通常的采用的方式是把HeightMap和SplatMap(Layer Mask)导入到引擎的地形系统里 ...