.net core使用ef core操作mysql数据库
新建.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数据库的更多相关文章
- 以EF形式操作mysql数据库
1.引入Nuget包: 2.书写EF操作上下文 public class MySqlContext:DbContext { protected override void OnConfiguring( ...
- 在.net core web 项目中操作MySql数据库(非ORM框架,原生sql语句方式)
本案例通过MySql.Data和Dapper包执行原生sql,实现对数据库的操作. 操作步骤: 第1步:在MySql数据库中新建表User(使用Navicat For MySql工具) 建表语句: c ...
- .NET Core Dapper操作mysql数据库
前言 现在ORM盛行,市面上已经出现了N款不同的ORM套餐了.今天,我们不谈EF,也不聊神马黑马,就说说 Dapper.如何在.NET Core中使用Dapper操作Mysql数据库呢,让我们跟随镜头 ...
- ASP.NET Core使用EF Core操作MySql数据库
ASP.NET Core操作MySql数据库, 这样整套环境都可以布署在Linux上 使用微软的 Microsoft.EntityFrameworkCore(2.1.4) 和MySql出的 MySql ...
- .NET 5/.NET Core使用EF Core 5连接MySQL数据库写入/读取数据示例教程
本文首发于<.NET 5/.NET Core使用EF Core 5(Entity Framework Core)连接MySQL数据库写入/读取数据示例教程> 前言 在.NET Core/. ...
- .net core使用orm操作mysql数据库
Mysql数据库由于其体积小.速度快.总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库.MySQL是一个多用户.多线程的关系型数据库管理系 ...
- net Core 通过 Ef Core 访问、管理Mysql
net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...
- 使用EF操作Mysql数据库中文变问号的解决方案
问题场景:使用Entity Framework 6.0 操作Mysql数据库,中文保存至数据库后全部变成问号.但是使用Mysql API却不会. 原因排查:首先想到的肯定是数据库编码问题,一次查询了表 ...
- ASP.NET CORE 使用 EF CORE访问数据库
asp.net core通过ef core来访问数据库,这里用的是代码优先,通过迁移来同步数据库与模型. 环境:vs2017,win10,asp.net core 2.1 一.从建立asp.net c ...
- Dapper操作MySQL数据库获取JSON数据中文乱码
前言 在项目中利用Dapper将JSON数据存储到MySQL数据库,结果发现JSON数据中的中文乱码,特此记录,希望对存储JSON的童鞋能有所帮助,文中若有错误之处,还望批评指正. Dapper获取J ...
随机推荐
- Android开发导出apk报错:Unable to build: the file dx.jar was not loaded from the SDK folder
问题背景 此问题一般出现在,同时使用了Eclipse和Android Studio,eclipse是不会去下载最新的Android的相关tools,但是studio有时候会自动更新最新的build-t ...
- Python装饰器用法
在Python中,装饰器一般用来修饰函数,实现公共功能,达到代码复用的目的.在函数定义前加上@xxxx,然后函数就注入了某些行为,很神奇!然而,这只是语法糖而已. 场景 假设,有一些工作函数,用来对数 ...
- iOS 开发网络篇—监测网络状态
iOS开发网络篇—监测网络状态 一.说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能) (2)根据用户的网络状态进行 ...
- [Java并发编程(三)] Java volatile 关键字介绍
[Java并发编程(三)] Java volatile 关键字介绍 摘要 Java volatile 关键字是用来标记 Java 变量,并表示变量 "存储于主内存中" .更准确的说 ...
- go语言的排序和去重
go语言的排序: https://blog.csdn.net/u010983881/article/details/52460998 go语言去重: https://blog.csdn.net/qq_ ...
- unicode、utf8、字符串字面值
发现好多新人都不明白,或者说没有直观的感受,其实很简单. 简单的说,unicode是一种将全球文字都涵盖的字典 - 可以认为每个字符都有一个数字索引. 比如可以这样(假设):'a' 的索引是13,'我 ...
- Android多种格式的异步解压/压缩解决方案
前言 最近由于项目需要,需要我谅解一下关于在移动平台的解压功能,在移动平台解压,我个人感觉是没有太大必要的,毕竟手机的性能有限.但是,不口否认,移动端的解压功能又是必备的,因为如果对于一些资源管理器类 ...
- google的python语言规范
Python语言规范 Lint Tip 对你的代码运行pylint 定义: pylint是一个在Python源代码中查找bug的工具. 对于C和C++这样的不那么动态的(译者注: 原文是less ...
- python 笔记 week1-- if while for
1.添加环境变量 windows要加环境变量.linux若升级版本不一致, #!/usr/bin/env python 调用环境变量中的python #!/usr/bin/python 调用系统中默认 ...
- a排兵布阵
来源hdu1166 C国的死对头A国这段时间正在进行军事演习,所以C国间谍头子Derek和他手下Tidy又开始忙乎了.A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任务就是要监视这些工兵 ...