1. 首先从 https://aspnetboilerplate.com/ 创建个demo, 注意:abp现在有2个网站创建模板, 另一个是 http://abp.io/。 区别是abp.io是基于.net core 3.0以上的。因为项目需求, 此处用的还是第一个网站创建。
2. 改造EntityFrameworkCore工程的引用,目前是用的.net core 2.2。具体最终的引用如下
3. 该种EntityFrameworkCore工程里DbContextOptionsConfigurer 类。 如果没有指定mysql的版本, 最终在update-database时可能会出现datetime(6) 语法错误
public static class DbContextOptionsConfigurer
{
public static void Configure(
DbContextOptionsBuilder<CollaborationPlatformDbContext> dbContextOptions,
string connectionString
)
{
/* This is the single point to configure DbContextOptions for CollaborationPlatformDbContext */
dbContextOptions.UseMySql(connectionString,
mysqlOptions =>
{
//此处指定mysql版本是因为code first生成的msyql 语法和版本相关, 比如DateTime
mysqlOptions.ServerVersion(new Version(5, 5), ServerType.MySql);
});
}
public static void Configure(
DbContextOptionsBuilder<CollaborationPlatformDbContext> builder,
DbConnection connection)
{
builder.UseMySql(connection,
mysqlOptions =>
{
//此处指定mysql版本是因为code first生成的msyql 语法和版本相关, 比如DateTime
mysqlOptions.ServerVersion(new Version(5, 5), ServerType.MySql);
});
}
}
4. 在.Core工程中定义实体
public class Abc: Entity<int>
{
private string _name = string.Empty;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
}
5. 在EntityFrameworkCore工程里定义对应的CodeFirst映射逻辑类
public class AbcConfiguration : IEntityTypeConfiguration<Abc>
{
public void Configure(EntityTypeBuilder<Abc> builder)
{
builder.ToTable("Abc");
}
}
6. 在EntityFrameworkCore工程里的xxxDbContext.cs内, 定义表
//Add DbSet properties for your entities...
public virtual DbSet<Abc> Abcs
{
get; set;
}
7. 继续在xxxDbContext类的OnModelCreating方法中添加刚才的code first 逻辑
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
builder.ApplyConfiguration(new AbcConfiguration());
}
到此, 整个mysql改造及初步的表定义及持久化demo就ok了, 现在需要创建对应的mysql
-
在某个启动工程里添加mysql的connectionstring, 比如web工程或者console工程里的app.config 或者appsettings.json
-
在包含connectionstring的工程上右键选择 “设为启动项目”
-
在vs顶部菜单上,选择“工具”/“Nuget 包管理器” / “程序包管理器控制台”, 也就是常说的PMC
-
在打开的PMC中的顶部“默认项目”中选择EntityFrameworkCore工程, 这个步骤非常重要。 不然会报错“Your target project '' doesn't match your migrations assembly ''. Either change your target project or change your migrations assembly.”
-
在PMC中敲入Add-Migration "Init_Create"命令
最终会在选择的工程中创建Migrations文件夹, 并生成数据库创建的类, 我们需要打开看看里面的表名、列名、列定义、表之间的关系是否符合我们的预期。
6. 接下来我们就可以在PMC中敲入Update-Database命令, 用来调用migration的类来创建数据库及表