我有以下代码来创建实体,并为它们添加数据,以便在asp.net mvc应用程序中使用。我使用的是代码优先和实体框架。我生成控制器并运行应用程序,但在index.cshtml页面上,种子数据所在的列表为空
public class MyContext : DbContext
{
public MyContext() : base("dataDb") {}
public DbSet<Owner> Owners { get; set; }
public DbSet<Pet> Pets { get; set; }
}
public class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
// seed database here
context.Owners.AddOrUpdate(
new Owner()
{
//name=,
//id=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,
},
new Pet()
{
//id=,
//name=,
}}
},
new Owner()
{
//id=,
//name=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,,
}
}
}
);
context.SaveChanges();
}
}
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public virtual List<Pet> Pets { get; set; }
}
public class Pet
{
public int PetId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public virtual Owner Owner { get; set; }
}
}
我找到了这个问题的解决方案:
Database.SetInitializer(new MyInitializer()); //important for seed to work
将此行添加到上下文构造函数:
public MyContext() : base("dataDb") {}
您也可以将其添加到web.config中。在部署时,您可以使用配置转换器轻松地将其从web.config中删除。
<entityFramework>
<contexts>
<context type="MyProject.MyContext, MyProject">
<databaseInitializer type="MyProject.MyInitializer, MyProject" />
</context>
</contexts>
...
</entityFramework>
<connectionStrings>
<add name="MyContext" connectionString="Data Source=(LocalDb)MSSQLLocalDB;Initial Catalog=OwnersPets; AttachDBFilename=|DataDirectory|OwnersPets.mdf; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionString>
与localDb 一起使用的示例conn字符串