c# - 模型未更改时,代码优先实体框架删除并重新创建表
问题描述
我有以下类(继承自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;
}
我确信这取决于我做了一些愚蠢的事情,但是因为每次我清理 => 重建 => 运行项目时都不会发生这种情况,所以我发现很难找到问题所在。
回顾一下:
- 我有一个没有改变的模型(包括命名空间等,我创建的类中模型的属性类型等)
- 有时,当我运行项目时,与该模型相关的表会被删除并重新创建。
如果有人能帮助我找出我可以从哪里开始寻找问题的根本原因,我将不胜感激。如果您需要我发布我的代码,请告诉我。
谢谢。
解决方案
你可以改变
AutomaticMigrationsEnabled = false;
然后,仅在您使用指向实体项目的控制台对其进行更改时更新您的模型:
add-migration [Migrator_Name]
update-database
推荐阅读
- php - 未保存在数据库中的信息
- random - Lua - 在每次运行/事件中随机选择 3 个数字(共 250 个),但不包括一个
- android - 如何在“2018-08-07T19:37:24+05:30”模式Android中转换日期时间?
- php - 为什么在 PHP 中回显连接时无法执行加法
- php - 实时设置 PayPal PHP 应用程序
- xml - WiX 引导程序。无法连接 msi 包
- angular - 如何使用 Angular 5 读取文件内容?
- android - 在滚动内容和显示比较方面,webview 是否优于回收站视图?
- python-3.x - AttributeError:“NoneType”对象没有属性“驱动程序名”
- php - 通过Ajax删除图像而不重新加载页面laravel