首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法首先使用EF-Code重新创建数据库。

无法首先使用EF-Code重新创建数据库。
EN

Stack Overflow用户
提问于 2012-05-12 07:57:25
回答 1查看 6.8K关注 0票数 0

我正在努力学习EF Code first。最初,我在ModelClass上尝试了使用ModelClass的所有约束。工作也很好。

但是现在我尝试使用独立配置文件使用Fluent API,但是它无法重新创建数据库并抛出此错误

无法检查

模型兼容性,因为数据库不包含模型元数据。只能检查使用代码优先或代码优先迁移创建的数据库的模型兼容性。

,这是我的模型

代码语言:javascript
运行
复制
public Class User
{
    public string UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

这里是我的DbContext

代码语言:javascript
运行
复制
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类

代码语言:javascript
运行
复制
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方法中,即

代码语言:javascript
运行
复制
//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建议。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-12 17:53:39

该错误发生在应用程序的其他部分,因为它创建了数据库模式,但是表dbo._MigrationHistory无法在sqlServer上创建,也就是说,由于所需的信息不存在,Codefirst无法删除数据库。当我删除数据库时,mst起作用了,但我猜浏览器正在显示缓存的数据。当我重新启动系统的时候一切都很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10562004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档