MySQL official MySQL EF provider is in preview stage
You can choose to download the official MySQL or use a third-party NuGet package for installation
MySQL official MySQL EF provider:
Install-package MySql.Data.EntityFrameworkCore
Or use a third party:
Install-package POMELO.ENTITYFRAMEWORKCORE.MYSQL
There's no big difference between the two.
Create a class first, assuming the Person.cs
1 Public class Person2 {3 Public LongId {Get;Set; }4 Public stringName {Get;Set; }5 Public intAge {Get;Set; }6 Public BOOL? Gender {Get;Set; }7}
Next Write DbContext:
1 usingMicrosoft.entityframeworkcore;2 3 namespaceEfcore4 {5 Public classMydbcontext:dbcontext6 {7 PublicDbset<person> Persons {Get;Set; }8 protected Override voidonconfiguring (Dbcontextoptionsbuilder optionsbuilder)9 {Ten Base. Onconfiguring (Optionsbuilder); OneOptionsbuilder.usemysql ("Server=127.0.0.1;database=testdb;uid=root");//Configuring the connection string A } - protected Override voidonmodelcreating (ModelBuilder ModelBuilder) - { the Base. Onmodelcreating (ModelBuilder); - varEtperson = Modelbuilder.entity<person> (). ToTable ("t_persons"); -Etperson.property (e = e.age). IsRequired ();//do not write isrequired, default is nullable -Etperson.property (E =e.gender). IsRequired (); +Etperson.property (e = e.name). Hasmaxlength ( -). IsRequired (); - } + A } at}
Where the configuration for database columns is similar to the. NET Framework's EF
Then add the following code to the program:
1 usingSystem;2 3 namespaceEfcore4 {5 class Program6 {7 Static voidMain (string[] args)8 {9 using(Mydbcontext CTX =NewMydbcontext ())Ten { OnePerson p =NewPerson (); AP.name ="Zhao Yun"; -P.age = the; -P.gender =true; the CTX. Persons.add (p); - CTX. SaveChanges (); - Console.WriteLine (p.id); - } + Console.readkey (); - } + } A}
After running, the newly added data ID will be printed, and inserting Chinese data in the console will appear garbled
But it doesn't matter, we're not going to be in the console to develop. NET core projects
Final file structure
. Net Core 2.0 uses EF to connect to MySQL database