.Net Core 2.0 使用EF連接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<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 項目

最終文件結構

 

 EF Core暫時不支持多對多,如果需要使用多對多的配置,可以自動創建第三張表,通過配置兩個一對多的結構來配置多對多


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM