我遇到一个奇怪的问题,每当我更改实体的任何一个时,我的 EF 自动迁移都会从所有 表中删除所有数据。
我见过类似的 question然而,对于我的生活,我无法从链接中得出我自己的实现中缺少的东西。
请注意,该应用程序工作得非常好,通过 EF 检索数据并将其保存到 mysql 数据库中 - 每次我想修改实体时都必须重新创建所有数据,这真是一件很烦人的事。
我正在使用 EF6.0 和 MySql 数据库。
上下文.cs
namespace Dock.Models
{
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DockContext : DbContext
{
public DockContext(): base("name=DockContext")
{
Database.SetInitializer(new DockInitializer());
}
public virtual DbSet<Profile> Profiles { get; set; }
public virtual DbSet<Dock> Docks { get; set; }
public virtual DbSet<Crate> Crates { get; set; }
public virtual DbSet<Subscription> Subscriptions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
配置.cs
internal sealed class Configuration : DbMigrationsConfiguration<DockContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
CodeGenerator = new MySqlMigrationCodeGenerator();
}
protected override void Seed(DockContext context)
{
Profile admin = new Profile {
NotAPrimaryId = 168879070,
DisplayName = "Admin101"
};
context.Profiles.AddOrUpdate(a => a.NotAPrimaryId , admin);
context.SaveChanges();
}
}
以及实体的 Dock.cs
之一的示例namespace Dock.Entities
{
public class Dock
{
[Key]
public int DockId { get; set; }
public int ProfileId { get; set; }
public int GameId { get; set; }
public string GameData { get; set; }
public bool Active { get; set; }
// Navigational Properties
[ForeignKey("CrateId")]
public virtual List<Crate> Crates { get; set; } = new List<Crate>();
}
}
最佳答案
EF 将 create migration classes for you .您不必手写它们。
根据我的经验,当不同的团队成员在不同时间提交更新时,自动迁移可能会导致问题。
我还不得不多次手动编辑生成的基于代码的迁移,这是自动迁移无法完成的。
我建议切换到手动迁移,以便您可以完全了解和控制迁移过程。
关于c# - EF 在自动迁移期间保留现有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079743/