当前位置:Gxlcms > 数据库问题 > .Net Core 2.0 使用EF连接MySQL数据库

.Net Core 2.0 使用EF连接MySQL数据库

时间:2021-07-01 10:21:17 帮助过:4人阅读

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<Person> 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<Person>().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 项目

最终文件结构

技术分享图片

 

.Net Core 2.0 使用EF连接MySQL数据库

标签:text   net   png   blog   stat   接下来   soft   color   string   

人气教程排行