本文写于2016年12月18日,同样也是记录了一下遇到的问题,深层核心的问题并没有探寻,只是找到了现象级的解决方法,做个备查。
在之前,我创建了一个名为 WebAppIdentity 的 Identity2 官方示例项目,并且介绍了如何将数据库切换到已有数据库上。
不过今天再继续使用的时候却报了如下错误:
“/WebAppIdentity”应用程序中的服务器错误。
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.NotSupportedException: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
之前一直以为这个问题解决了,可没想到今天又出现了,仔细看了下上面的提示,没找到很有用的信息,只好把第一段的英文 Google 一下了,在 StackOverflow 上找到一个答案,但是描述的问题和第一个问题基本不太相关,惯性地往下拉了几条答案,看到一段熟悉的代码,就是在前文中提到的更换为已有数据库的地方,仔细看了两眼,回答者提到了如下内容:
If, like me, this is caused by starting with Code First and changing to Database First development mid-project.. this is all caused by one simple line. If you need to keep your database and its data comment out the following line:
public class ApplicationDbContext: IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(): base("DefaultConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
// 在这里将下面这一行注释掉
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
This will happen often in when starting out with the built in identity models. Once you get them working, you can remove that line to keep it intact yet retain the functionality. If your model changes, however, your database will have to be configured to match.. something you are doing in Database First development anyway!
好了,说得很清楚了,大意就是在程序第一次运行时,这段代码将使用 CodeFirst 的方式为你创建相关的用户体系数据库,而在数据库建好之后,再次运行程序时,这段代码会继续再执行一次,这时就会报错了。所以为了在 DatabaseFirst 的情况下让程序正常运行,需要在数据库建好之后将这句代码注释或删掉。