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