迁移∶代码先行,现有代码再有数据库;数据库随着业务变化迁移改变;
迁移命令:
1.可以通过EfCore带有的api来完成从代码生成数据库
确保以上的都存在
MigrationDBContext.cs
public partial class MigrationDBContext : DbContext
{
public MigrationDBContext()
{
}
public MigrationDBContext(DbContextOptions<MigrationDBContext> options)
: base(options)
{
}
public virtual DbSet<UserDatum> UserData { get; set; }
/// <summary>
/// 需要连接数据库所用的配置
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=.;Database=MigrationDada;Trusted_Connection=True;User
Id=sa;Password=123");
}
}
/// <summary>
/// 这里是配置实体和数据库之间的映射关系
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDatum>(entity =>
{
entity.HasKey(e => e.PId);
entity.Property(e => e.PId)
.ValueGeneratedNever()
.HasColumnName("p_Id");
entity.Property(e => e.PAge)
.HasMaxLength(50)
.HasColumnName("p_Age");
entity.Property(e => e.PInfo)
.HasMaxLength(50)
.HasColumnName("p_Info");
entity.Property(e => e.PName)
.HasMaxLength(50)
.HasColumnName("p_Name");
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
UserDatum.cs
public partial class UserDatum
{
public int PId { get; set; }
public string PName { get; set; }
public string PAge { get; set; }
public string PInfo { get; set; }
}
应用
try {
using (MigrationDBContext context=new MigrationDBContext())
{
context.Database.EnsureDeleted();//如果有对应的数据库,就删除
context.Database.EnsureCreated();//创建数据库
}
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
2.迁移
1).在控制台输入命令 add-migration Init001
成功之后会出现一个Migrations文件夹,其中是迁移文件,可以通过迁移文件生成数据库。
2).在控制台输入 update-database
结果
3).应用
try {
using (MigrationDBContext context = new MigrationDBContext())
{
//添加信息
context.UserData.Add(new UserDatum()
{
PId = 1,
PName = "hello",
PAge = "892",
PInfo = "what happen to you?"
});
//保存修改
context.SaveChanges();
}
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}