我首先在一个简单的 MVC3 应用程序中使用 EF4 代码。上下文对象正在拾取正确的连接字符串,并调用初始化程序构造函数,就像 OnModelCreating 方法一样,但从未调用种子方法并且未创建数据库。任何想法为什么?
protected void Application_Start()
{
Database.SetInitializer<SchoolContext>(new SchoolInitializer());
SchoolContext context = new SchoolContext();
context.Database.CreateIfNotExists();
...
}
public class SchoolInitializer : DropCreateDatabaseAlways<SchoolContext>
{
public SchoolInitializer()
{
}
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student {StudentId = Guid.NewGuid(), Name = "Carson" },
new Student {StudentId = Guid.NewGuid(), Name = "Meredith" }
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
}
}
public class Student
{
[Key]
public Guid StudentId;
public string Name;
}
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
配置:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=|DataDirectory|School.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
我认为抛出的异常只是抱怨尚未创建数据库:
[ModelValidationException:在模型生成过程中检测到一个或多个验证错误:
.Data.Edm.EdmEntityType: : EntityType 'Student' 没有定义键。定义此 EntityType 的键。System.Data.Edm.EdmEntitySet:EntityType:EntitySet “Students”基于没有定义键的“Student”类型。