前言
都是自己使用的代码,可以达到EF框架创建数据库的作用,简单记录代码和过程。
引用
引用了下图中的两个包,
代码内容
创建一个表结构的类
[Table("Note")]
public class Note :BindableBase
{
private string noteID;
[Key] 设置主键
public string NoteID
{
get { return noteID; }
set { noteID = value; RaisePropertyChanged(); }
}
private string notePath;
public string NotePath
{
get { return notePath; }
set { notePath = value; RaisePropertyChanged(); }
}
}
其中[Key]就是设置主键,还有其他的属性可以设置,此处不做赘述。
创建一个类用于管理数据库连接和执行数据库操作,但是必须要继承DbContext 类
public class MyDbContext : DbContext
{
public DbSet<Note> Notes { get; set; }
// 其他 DbSet 属性...
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql("Server=localhost;Port=3306;Database=You_DbName;Uid=root;Pwd=Password;", new MySqlServerVersion(new Version(8, 0, 29)));
}
}
其中, optionsBuilder.UseMySql(“Server=localhost;Port=3306;Database=You_DbName;Uid=root;Pwd=Password;”, new MySqlServerVersion(new Version(8, 0, 29)));字符串是连接语句,数据库的账号和密码是需要提前建立好的。
打开程序包管理器控制台,并且执行命令
程序包管理器控制台的位置
执行命令
运行以下命令来启用数据库迁移:
Enable-Migrations
然后,运行以下命令来生成迁移文件:
Add-Migration InitialCreate
运行以下命令将迁移应用到数据库:
Update-Database
结束
按上述操作就已经可以创建和修改数据库了,其中和会有细节,详细的请查看其他资料