【发布时间】:2018-10-12 14:55:21
【问题描述】:
我有以下类(继承自 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;
}
我确信这是因为我做了一些愚蠢的事情,但由于每次我清理 => 重建 => 运行项目时都不会发生这种情况,我发现很难找到问题所在。
回顾一下:
- 我有一个未更改的模型(包括命名空间等,我创建的类中模型的属性类型等)
- 有时当我运行项目时,与该模型相关的表会被删除并重新创建。
如果有人能帮助我找出我可以从哪里开始寻找问题的根本原因,我将不胜感激。如果您需要我再发布我的代码,请告诉我。
谢谢。
【问题讨论】:
-
你能发布 MigrateDatabaseToLatestVersion 类的代码吗?想要确保您不是从
DropCreateDatabaseAlways或DropCreateDatabaseIfModelChanges派生该类。 -
嗨@DipenShah,该课程只是标准的
System.Data.Entity.MigrateDatabaseToLatestVersion课程。 -
完全忘记了那个!您是否可以创建一个小项目来复制该问题。我使用您指定的类创建了一个小项目,但它的行为符合预期。
-
除了
AutomaticMigrationsEnabled = true;,你试过加AutomaticMigrationDataLossAllowed = false;吗?您有可以发布的Seed()方法吗? -
您正在检查是否通过“在表上重复发送选择查询”来删除/重新创建表!!?为什么?您的表中没有任何数据吗?如果你没有丢失数据,那么表就没有被删除/重新创建。
标签: c# entity-framework-6 automatic-migration