我刚开始使用EF v5的新应用程序
我在SQL Server中创建了一个没有任何表的数据库。我试图让EF从模型代码创建表,但在尝试执行时发生错误:
c.Database.Initialize(true);
以下是错误:
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.
我读到了添加
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
到上下文类可能会修复它,但在我的情况下它没有。对此进行故障排除我不知道下一步该去哪里。
问题
我不应该提前创建数据库吗? 任何想法都会被彻底赞赏!
以下是Global.asax中的代码
protected void Application_Start()
{
Database.SetInitializer(new ClubLocatorInitializer());
LocatorContext c = new LocatorContext();
c.Database.Initialize(true);
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
以下是我的上下文类中的代码
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using ClubLocator.Models;
using ClubLocator.Models.ViewModels;
namespace ClubLocator.DAL
{
public class LocatorContext : DbContext
{
public DbSet<Prospect> Prospects { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
这是我的初始化程序
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using ClubLocator.Models;
namespace ClubLocator.DAL
{
public class ClubLocatorInitializer : DropCreateDatabaseIfModelChanges<LocatorContext>
{
protected override void Seed(LocatorContext context)
{
var prospect = new List<Prospect>
{
new Prospect{
FirstName = "John",
LastName = "Smith",
Email = "jsmith@example.com"
}
};
prospect.ForEach(r => context.Prospects.Add(r));
context.SaveChanges();
}
}
}