Reputation: 5476
I am using EF4 code first within a simple MVC3 application. The correct connection string is being picked up by the context object, and the initializer constructor gets called, as does the OnModelCreating method, but the seed method is never called and the database is not created. Any ideas why?
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>();
}
}
Config:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=|DataDirectory|School.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
The exception thrown I think is just complaining that the database has not been created:
[ModelValidationException: One or more validation errors were detected during model generation:
.Data.Edm.EdmEntityType: : EntityType 'Student' has no key defined. Define the key for this EntityType. System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Students� is based on type �Student� that has no keys defined.
Upvotes: 2
Views: 1049
Reputation: 39491
Your model is invalid - Student
entity has no key defined, and database creation is not triggered until model is valid.
You should add accessors to your StudentId
. This will make model valid and trigger database creation
public Guid StudentId { get; set; }
Upvotes: 4