can I query context from within seed method of context initializer
I am initializing my database from a bunch of sql scripts. Then I would like to query the data when adding more data so foreign key relations match up. Yet in my example, the "painting" variable always ends up null even though the data is there. Is is possible to query the data inside this seed method? Do I have to commit the data or something?
class ArtConvergenceInitializer : DropCreateDatabaseIfModelChanges<ArtConvergence>
{
protected override void S开发者_运维知识库eed(ArtConvergence context)
{
var seedfilePath = System.Configuration.ConfigurationManager.AppSettings["PathToInitializationScript"].ToString();
foreach(var file in System.IO.Directory.EnumerateFiles(seedfilePath,"*.sql"))
{
var sqlCommand = System.IO.File.ReadAllText(file);
context.Database.ExecuteSqlCommand(sqlCommand);
context.SaveChanges();
}
var painting = context.Mediums.Where(x => x.MediumType == "Painting" && x.SpecificMedium == null).FirstOrDefault();
var oilOnCanvas = context.Mediums.Where(x => x.MediumType == "Painting" && x.SpecificMedium == "oil on canvas").FirstOrDefault();
}
Once you use direct SQL scripts it should not be too hard to write SQL script which will correctly insert data with existing foreign keys. I did it many times. Keep your initialization logic together.
精彩评论