EFCore模型驱动+Mysql

1、建立Web.Models类库并通过NuGet安装EFCore需要包

    MySql.EntityFrameworkCore 7.0.5

    Microsoft.EntityFrameworkCore.Tools 7.0.5

    Microsoft.EntityFrameworkCore.Design 7.0.5

注意版本最好一致,我安装的时候,MySql.EntityFrameworkCore 版本低,运行报错了。

2、建立实体类 Book.cs

 

 1 namespace Web.Models
 2 {
 3     public class Book
 4     {
 5         public long Id { get; set; }    
 6         public string Title { get; set; }
 7         public DateTime PubTime { get; set; }
 8         public double Price { get; set; }
 9         public string AuthorName { get; set; }
10     }
11 }

3、对Book类进行属性配置

 1 namespace Web.Models
 2 {
 3     internal class BookEntityConfig:IEntityTypeConfiguration<Book>
 4     {
 5         public void Configure(EntityTypeBuilder<Book> builder) 
 6         {
 7             builder.ToTable("T_Books");
 8             builder.Property(e => e.Title).HasMaxLength(50).IsRequired();
 9             builder.Property(e=>e.AuthorName).HasMaxLength(20).IsRequired();
10         }   
11     }
12 }

4、建立可操作的ORM

 1 namespace Web.Models
 2 {
 3     public class TestDbContext : DbContext
 4     {
 5         public DbSet<Book> Books { get; set; }
 6         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 7         {
 8             string connStr = "server=localhost;port=3306;database=virtual_medicine;user=root;pwd=qwe123;charset=utf8;";
 9             optionsBuilder.UseMySQL(connStr);
10         }
11         protected override void OnModelCreating(ModelBuilder modelBuilder)
12         {
13             base.OnModelCreating(modelBuilder);
14             modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
15         }
16     }
17 }

5、NuGet控制台创建表

PM> Add-Migration InitialCreate
Build started...
Build succeeded.
To undo this action, use Remove-Migration.

 

PM> Update-database
Build started...
Build succeeded.
Applying migration '20230807102353_InitialCreate'.
Done.

注:红色背景为输入命令,后面的为执行后控制台打印出来的命令。

 6、修改Mysql编码格式(主要解决插入中文报错问题)

输入 show variables like 'character%' 查看数据库的编码为latin1

     

数据命令 ALTER DATABASE `table` CHARACTER SET utf8 将数据库编码格式改为utf8

注意:如果建表的时候没有改,删除重新建立才生效。

7、执行控制器代码像表中插入数据

1  using TestDbContext ctx = new TestDbContext();
2             var b1 = new Book { AuthorName = "吴军", Title = "编程之美", Price = 59.8, PubTime = new DateTime(2019, 3, 1) };
3             var b2 = new Book { AuthorName = "FrederickP.Brooks.Jr.", Title = "人月神话", Price = 112, PubTime = new DateTime(2020, 5, 1) };
4 
5             ctx.Books.Add(b1);
6             ctx.Books.Add(b2);
7 
8             ctx.SaveChanges();

 

参考地址:https://blog.csdn.net/seven0000000007/article/details/130401692

                  https://blog.csdn.net/AlinaQ05/article/details/126102699

 

posted @ 2023-08-07 19:06  Fast & Furious  阅读(55)  评论(0)    收藏  举报