我尝试使用Entity Framework填充数据库。我使用Seed
覆盖并使用DbContext
中的set initializer。当我从头开始创建数据库时,它似乎不会在!
public class PokemonDatabaseInitializer : CreateDatabaseIfNotExists<PkmnContext>
{
protected override void Seed(PkmnContext context)
{
var pkm = new Pokemon
{
Id = 25,
DisplayName = "Pikachu",
RegionId = 1
};
var region = new PokemonRegion
{
Id = 1,
Kanto = true,
};
var location = new PokemonLocation
{
AreaFound = "Viridian Forest",
Id = 1
};
context.Pokemons.Add(pkm);
context.PokemonRegions.Add(region);
context.PokemonLocations.Add(location);
context.SaveChanges();
base.Seed(context);
}
}
public class PkmnContext : DbContext
{
public PkmnContext()
{
Database.SetInitializer(new PokemonDatabaseInitializer());
}
public DbSet<Pokemon> Pokemons { get; set; }
public DbSet<PokemonRegion> PokemonRegions { get; set; }
public DbSet<PokemonLocation> PokemonLocations { get; set; }
}
答案 0 :(得分:0)
你需要打电话
从包管理器控制台更新的数据库
。在应用任何迁移后,也可以从代码中调用它
请注意,每次调用它时都会播种数据,所以如果项目已经存在,我会添加一些检查