由于数据库初始化失败,我不得不在不同的 MVC 4 代码优先技术教程的相同阶段停下来。
使用连接
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-DbTestApp-20130205173443;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-DbTestApp-20130205173443.mdf" providerName="System.Data.SqlClient" />
我什至无法创建或管理我想从我的模型中生成的数据库
public class Category
{
public int Id { get; set; }
[Required]
[MinLength(4)]
[MaxLength(64)]
public string Name { get; set; }
public virtual IEnumerable<Article> Articles { get; set; }
}
public class Article
{
public int Id { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
[Required]
[MinLength(4)]
[MaxLength(64)]
public string Title { get; set; }
[Required]
[MinLength(16)]
[MaxLength(1024)]
[DataType(DataType.MultilineText)]
public string Content { get; set; }
[Required]
[Display(Name = "Post Anonymous?")]
public bool IsAnonymous { get; set; }
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
public virtual IEnumerable<Comment> Comments { get; set; }
}
public class Author
{
public int Id { get; set; }
[MinLength(3)]
[MaxLength(64)]
public string AuthorName { get; set; }
public virtual IEnumerable<Article> Articles { get; set; }
public virtual IEnumerable<Category> Categories { get; set; }
}
public class Comment
{
public int Id { get; set; }
public int ArticleId { get; set; }
public virtual Article Article { get; set; }
[Required]
[MinLength(3)]
[MaxLength(64)]
public string Author { get; set; }
[MaxLength(64)]
public string Title { get; set; }
[Required]
[MinLength(4)]
[MaxLength(512)]
public string Content { get; set; }
}
使用下面的上下文
public class BlogContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Article> Articles { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Comment> Comments { get; set; }
public BlogContext()
: base("DefaultConnection")
{
Configuration.ProxyCreationEnabled = false;
}
}
我还在 Global.asax Application_Start() 方法中设置了初始化程序:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<BlogContext>());
当我试图打电话时问题就来了
var articles = db.Articles.Include(a => a.Category).Include(a => a.Author);
在我的 BlogController 的 Index() 方法中返回一个包含存储文章列表的视图。每次调用数据库相关方法时都会发生这种情况,错误消息是:
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.
在教程中,我没有发现任何关于此类问题的信息,而我阅读的解决方案也无法解决问题。
有任何想法吗?
谢谢