【问题标题】:Getting Error "The model backing the 'DBContext' context has changed since the database was created. "出现错误“支持 'DBContext' 上下文的模型自创建数据库以来已更改。”
【发布时间】:2014-10-13 08:23:46
【问题描述】:

我知道这个问题是重复的,我也找到了一个解决方案,但这是四年前的问题,我认为这些年来 EntityFramework 处于不同的水平,所以我想再次问这个问题。这是我找到并尝试在实体框架 5.0 上应用但不起作用的答案

The model backing the <Database> context has changed since the database was created

这是我的实体模型类第一个是这个

    public class Student
{
    public int StudentId {get; set;}
    [StringLength(250),Required]
    public string StudentName {get; set;}
    [StringLength(20),Required]
    public string Standard {get; set; }
    [StringLength(250),Required]
    public string Address {get; set; }
    [StringLength(250),Required]
    public string Emailid {get; set; }
    [StringLength(12),Required]
    public string Phoneno {get; set; }

}

第二个模型类就是这个

    public class Marks
{

    public int MarksID { get; set; }
    public int StudentId { get; set; }
    public int English { get; set; }
    public int Maths { get; set; }
    public int Science { get; set; }
    public int SocialStudy { get; set; }
    public int Hindi { get; set; }
    public int Total { get; set; }
    public Student student { get; set; }

}

这是我的上下文类

 public class DBContext:DbContext
{
    public DBContext()
    {
        Database.SetInitializer<DbContext>(new DropCreateDatabaseAlways<DbContext>());
    }

    public DbSet<Student> TbStudent { get; set; }
    public DbSet<Marks> TbMarks { get; set; }
}

我运行此代码并收到此错误

支持“DBContext”上下文的模型在创建数据库后发生了变化。考虑使用 Code First 迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。

请专家帮助我解决这个问题

【问题讨论】:

  • 嗯,在您的问题中,您有一个指向代码优先迁移教程的链接。你读了吗?

标签: entity-framework entity-framework-migrations


【解决方案1】:

代码优先迁移将帮助您解决此问题。但要以您的方式初始化数据库,您必须在 Database.SetInitializer 函数中将 DbContext 替换为 DBContext(即使用您的上下文类),如下所示。

  public class DBContext:DbContext
  {
       public DBContext()
       {
           Database.SetInitializer<DBContext>(new DropCreateDatabaseAlways<DBContext>());
       }
   }

希望这会有所帮助。

【讨论】:

  • 我多么愚蠢。我正在使用 Dbcontext 而不是我的班级,这是一个我没有注意到的小错误。现在我很生气自己浪费了 2 个小时来搜索这种小错误,谢谢... :)
  • @HarSimranKaur 这正是我近一个小时发生的事情。谢谢你们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 2014-04-19
  • 2011-04-05
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多