.net core linq mysql_.net core使用ef core操作mysql数据库

本文介绍了如何在.NET Core WebAPI项目中使用Entity Framework Core操作MySQL数据库,包括安装必要的NuGet包、配置DbContext、创建模型、设置连接字符串、数据库迁移以及控制器的实现。通过确保数据库存在或执行迁移命令,可以实现数据库的自动创建和更新。
摘要由CSDN通过智能技术生成

新建.net core webapi项目

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

安装后创建DataContext.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.EntityFrameworkCore;namespaceWebApplication4

{public classDataContext : DbContext

{public DataContext(DbContextOptions options) : base(options)

{

}public DbSet tbusers { get; set; }protected override voidOnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity();

}

}

}

TbUser.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations.Schema;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceWebApplication4

{public classTbUser

{

[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 voidConfigureServices(IServiceCollection services)

{

services.AddDbContext(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 voidConfigure(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, seehttps://aka.ms/aspnetcore-hsts.

app.UseHsts();

}

app.UseHttpsRedirection();

app.UseMvc();

context.Database.EnsureCreated();

}

添加UserController.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Mvc;namespaceWebApplication4.Controllers

{

[Produces("application/json")]

[Route("api/user")]public classUserController: ControllerBase

{private readonlyDataContext _context;publicUserController(DataContext context)

{this._context =context;

}//POST api/user

[HttpPost]public intPost(TbUser user)

{

_context.Add(user);

_context.SaveChanges();return 200;

}//GET api/user

[HttpGet]public ListGet()

{

_context.Database.EnsureCreated();var users =_context.tbusers;

List items = new List();foreach (var item inusers)

{

items.Add(item);

}returnitems;

}//GET api/user/5

[HttpGet("{id}")]public TbUser Get(intid)

{var u =_context.tbusers.Find(id);returnu;

}//DELETE api/user/5

[HttpDelete("{id}")]public int Delete(intid)

{var u = _context.tbusers.Remove(new TbUser() { ID =id });

_context.SaveChanges();return 200;

}//PUT api/user/5

[HttpPut("{id}")]public int Put(intid, TbUser user)

{var u =_context.tbusers.Update(user);

_context.SaveChanges();return 200;

}

}

}

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

如果用的是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[10403]

Entity Framework Core2.2.1-servicing-10028 initialized 'DataContext' using provider 'MySql.Data.EntityFrameworkCore'with options: None

Done. To undothis 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(150) NOT NULL,

`ProductVersion` nvarchar(32) NOT NULL,

PRIMARY KEY(`MigrationId`)

);

然后执行update-database

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

http://localhost:17800/api/user

返回json数据

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值