之前写过连接Sqlite的示例。使用Code First_故里2130的博客-CSDN博客_codefirst
这里依然使用ORM中的EntityFrameworkCore框架,ORM就是对象关系映射,用于实现面向对象编程语言里不同类型系统的数据之间的转换,也就是说,当我们的数据库改变了,可以很快速的进行切换,核心就是代码先行的。其实ORM分为很多种类,包括:
EF(Entity Framework),随着core的出现,也就是有了EFC(EntityFrameworkCore),SqlSugar,Dapper等等框架。
1.使用vs2022建立一个.net core web api项目
2.在nuget中搜索EntityFrameworkCore.MySql,进行安装,当我们用的是mysql,那么这里就选择mysql,当换数据库的时候,这里可以修改成别的数据库。
(注意版本问题,下面有坑)
3.再安装Microsoft.EntityFrameworkCore.Tools,主要是操作数据库的
4. 至此,我们需要安装的包就完成了,开始写代码
5. 建立一个user类,并且增加主键,这里可能有很多的类,依次建立即可
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using Microsoft.EntityFrameworkCore;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace mysqlCodeFirst
- {
- ///
- /// 用户表
- ///
- public class User
- {
- ///
- /// id
- ///
- [Key] //主键
- [MaxLength(10), MinLength(5)] //长度,最大10,最小5
- public int Id { get; set; }
- ///
- /// 姓名
- ///
- public string Name { get; set; }
- ///
- /// 年龄
- ///
- public int age { get; set; }
-
- }
- }
6.建立EFmysqlContext类,并且继承DbContext,手动初始化。这里就是上面建立类的一个汇总,类和类之间有关系,都要在这里进行体现,一个类就是一个表,也就是数据库中表和表的关系,1对1,1对多,多对多的关系,注释等等全部在这里体现。关系要写OnModelCreating方法中
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace mysqlCodeFirst
- {
- public class EFmysqlContext : DbContext
- {
- public EFmysqlContext(DbContextOptions
options ) : base(options) - {
-
- }
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- //这里写表(类)与表(类)之间1对1,1对多,多对多的关系
- }
-
- public DbSet
Users { get; set; } //这里有几个类就写几个类 -
- }
- }
7.在appsettings.json文件中进行配置数据库字符串,appsettings.json在core中就是配置文件,类似于app.config和web.config的作用。
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*",
- "ConnectionSetting": {
- "MySqlConnection": "Data Source=localhost;User ID=root;Password=123456;Database=mysqlCodeFirst;Allow User Variables=True;Charset=utf8;"
- }
- }
8.在Startup.cs进行注入,这里注入的是MySQL数据库,可以修改成别的数据库,也就是前面说的,更改数据库很方便
- services.AddDbContext
(options => - {
- options.UseMySQL(Configuration["ConnectionSetting:MySqlConnection"]);
- //这里可以修改别的数据库
- });
9. 现在开始迁入数据库中,在程序包管理器控制台中,输入Add-Migration xxx,xxx是迁移的名字。
注意:这里如果选择的包和mysql的版本不一样,可能会报错,报错就百度吧。本人选择的就不一样,导致报错问题,最后换了一下包的版本就可以了,所以在使用的时候,最好都使用最新版。
可见成功了,右侧有文件生成
10.再输入Update-Database,创建数据库完成
11.我们打开MySQL数据库,可以看到数据库和表
12. 接下来,我们进行使用
需要先进行注入
把代码写进控制类中
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace mysqlCodeFirst.Controllers
- {
- [ApiController]
- [Route("[controller]")]
- public class WeatherForecastController : ControllerBase
- {
- private static readonly string[] Summaries = new[]
- {
- "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
- };
-
- private readonly ILogger
_logger; - private readonly EFmysqlContext context;
-
- public WeatherForecastController(ILogger
logger, EFmysqlContext context ) - {
- _logger = logger;
- this.context = context;
- }
-
- [HttpGet]
- public IEnumerable
Get() - {
- User user = new User();
- user.age = 15;
- user.Id = 1;
- user.Name = "张三";
- context.Add(user);
- context.SaveChanges();
-
-
-
-
-
- var rng = new Random();
- return Enumerable.Range(1, 5).Select(index => new WeatherForecast
- {
- Date = DateTime.Now.AddDays(index),
- TemperatureC = rng.Next(-20, 55),
- Summary = Summaries[rng.Next(Summaries.Length)]
- })
- .ToArray();
- }
- }
- }
13.打开MySQL数据库,就能看到已经插入成功了。
官网说明