我正在努力学习EF Code first
。最初,我在ModelClass上尝试了使用ModelClass的所有约束。工作也很好。
但是现在我尝试使用独立配置文件使用Fluent API
,但是它无法重新创建数据库并抛出此错误
无法检查
模型兼容性,因为数据库不包含模型元数据。只能检查使用代码优先或代码优先迁移创建的数据库的模型兼容性。
,这是我的模型
public Class User
{
public string UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
这里是我的DbContext
public class AppContext : DbContext
{
public DbSet<User> Users { get; set; }
//Public constructor to Call DropCreateDatabaseIfModelChanges method
public AppContext()
{
//Calling the Method to ReCreate the database
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AppContext>());
}
//Overriding OnModelCreating Method to Configure the Model using Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configuration.Add(new UserConfiguration());
}
}
这是我的UserConfiguration类
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
//Using Fluent API to configure Model
HasKey(x => x.UserID);
Property(x => x.Username).IsRequired().HasMaximumLength(50);
Property(x => x.Password).IsRequired().HasMaximumLength(50);
}
}
我不知道我哪里错了。任何建议都是值得注意的。
注意:我使用的是EF 4.3.1
编辑
如果我将配置直接放在OnModelCreating
方法中,即
//Overriding OnModelCreating Method to Configure the Model using Fluent API
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Instead of Standalone Configuration file
//modelBuilder.Configuration.Add(new UserConfiguration());
//putting configuration here only
modelBuilder.Entity<User>().HasKey(x => x.UserID);
modelBuilder.Entity<User>().Property(x => x.Username).IsRequired().HasMaximumLength(50);
modelBuilder.Entity<User>().Property(x => x.Password).IsRequired().HasMaximumLength(50);
}
但是,我不知道为什么它不能使用独立的配置文件,即UserConfiguration
class.Any建议。
发布于 2012-05-12 17:53:39
该错误发生在应用程序的其他部分,因为它创建了数据库模式,但是表dbo._MigrationHistory
无法在sqlServer上创建,也就是说,由于所需的信息不存在,Codefirst无法删除数据库。当我删除数据库时,mst起作用了,但我猜浏览器正在显示缓存的数据。当我重新启动系统的时候一切都很好。
https://stackoverflow.com/questions/10562004
复制相似问题