我有以下类(继承自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;
}
我确定这是我做愚蠢的事情的原因,但是由于每次我清理=> rebuild =>运行该项目时都不会发生,所以我很难找到问题所在。
回顾:
如果有人能帮助我找到从哪里开始寻找问题的根本原因,我将不胜感激。如果您需要我再发布我的代码,请告诉我。
谢谢。
答案 0 :(得分:0)
您可以更改
AutomaticMigrationsEnabled = false;
,然后,仅当使用指向您的实体项目的控制台对模型进行更改时,才更新模型:
add-migration [Migrator_Name]
update-database