本文主要向大家介绍了MySQL数据库之.Net Core 2.0 使用EF连接MySQL数据库 ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。
MySQL官方mysql ef provider正在preview 阶 段
可以选择下载MySQL官方的,也可以使用第三方的NuGet包来进行安装
MySQL官方mysql ef provider:
Install-Package MySql.Data.EntityFrameworkCore
或者使用第三方:
Install-Package Pomelo.EntityFrameworkCore.MySql
两者使用起来没有太大区别
技术分享图片
先创建一个类,假设为Person.cs
1 public class Person
2 {
3 public long Id { get; set; }
4 public string Name { get; set; }
5 public int Age { get; set; }
6 public bool? Gender { get; set; }
7 }
接下来编写DbContext:
1 using Microsoft.EntityFrameworkCore;
2
3 namespace EFCore
4 {
5 public class MyDbContext:DbContext
6 {
7 public DbSet Persons { get; set; }
8 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
9 {
10 base.OnConfiguring(optionsBuilder);
11 optionsBuilder.UseMySQL("Server=127.0.0.1;database=testdb;uid=root");//配置连接字符串
12 }
13 protected override void OnModelCreating(ModelBuilder modelBuilder)
14 {
15 base.OnModelCreating(modelBuilder);
16 var etPerson = modelBuilder.Entity().ToTable("t_persons");
17 etPerson.Property(e => e.Age).IsRequired();//不写IsRequired,默认为可空
18 etPerson.Property(e => e.Gender).IsRequired();
19 etPerson.Property(e => e.Name).HasMaxLength(20).IsRequired();
20 }
21
22 }
23 }
其中对于数据库列的配置和.net framework的EF差不多
然后在Program里面添加如下代码:
1 using System;
2
3 namespace EFCore
4 {
5 class Program
6 {
7 static void Main(string[] args)
8 {
9 using (MyDbContext ctx = new MyDbContext())
10 {
11 Person p = new Person();
12 p.Name = "赵云";
13 p.Age = 15;
14 p.Gender = true;
15 ctx.Persons.Add(p);
16 ctx.SaveChanges();
17 Console.WriteLine(p.Id);
18 }
19 Console.ReadKey();
20 }
21 }
22 }
运行之后,会打印出新添加的数据id,在控制台中插入中文数据会出现乱码
不过没有关系,我们并不会在控制台中去开发.net core 项目
最终文件结构
本文由职坐标整理并发布,希望对同学们学习MySQL有所帮助,更多内容请关注职坐标数据库MySQL数据库频道!