首页 > 解决方案 > 模型未更改时,代码优先实体框架删除并重新创建表

问题描述

我有以下类(继承自BaseEntity其中只有一个int Id属性):

public class User : BaseEntity
{
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Created { get; set; }
    public DateTime? LastLogon { get; set; }
    public string LastIpAddress { get; set; }
    public string Password { get; set; }        
    public string CustomData { get; set; }
    public int FailedLogInAttempts { get; set; }
    public bool LockedOut { get; set; }
    public UserRole Role { get; set; }
}

它由以下类映射:

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        HasKey(t => t.Id);
        Property(t => t.Created);
        Property(t => t.CustomData);
        Property(t => t.Email);
        Property(t => t.FailedLogInAttempts);
        Property(t => t.FirstName);
        Property(t => t.LastIpAddress);            
        Property(t => t.LastLogon).IsOptional();
        Property(t => t.LastName);
        Property(t => t.LockedOut);
        Property(t => t.Password);            
    }
}

现在,有时当我运行项目时,我发现表被删除并重新创建。我可以这样说,因为我已经看到表在 SQL Server 中消失并重新出现(通过在表上反复发送选择查询以获得更好的方法!)。

我有一个自定义onModelCreating,因为我也从外部 DLL 中提取映射(用户不是来自外部 DLL)。我的自定义代码onModelCreating是:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    var typesToRegister = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
    .Where(type => !String.IsNullOrEmpty(type.Namespace))
    .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

    foreach (var type in typesToRegister)
    {
        dynamic configurationInstance = Activator.CreateInstance(type);
        modelBuilder.Configurations.Add(configurationInstance);
    }

    Database.SetInitializer<DataContext>(new MigrateDatabaseToLatestVersion<DataContext, Migrations.Configuration>());            
    base.OnModelCreating(modelBuilder);
}

我还使用以下内容自定义了我的迁移配置,以便迁移是自动的:

public Configuration()
{           
    AutomaticMigrationsEnabled = true;     
}

我确信这取决于我做了一些愚蠢的事情,但是因为每次我清理 => 重建 => 运行项目时都不会发生这种情况,所以我发现很难找到问题所在。

回顾一下:

如果有人能帮助我找出我可以从哪里开始寻找问题的根本原因,我将不胜感激。如果您需要我发布我的代码,请告诉我。

谢谢。

标签: c#entity-framework-6automatic-migration

解决方案


你可以改变

AutomaticMigrationsEnabled = false;

然后,仅在您使用指向实体项目的控制台对其进行更改时更新您的模型:

add-migration [Migrator_Name]
update-database

推荐阅读