0

I'm using a EF DbSet<FiveMinStockHistory>. And now, I need a code snippet showing how to implement the EF6+ method DbContext.OnModelCreating(DbModelBuilder modelBuilder) to populate a code-first database. I could not find any good examples.

public class FiveMinStockHistory
{
    public int Id { get; set; }
    public Dictionary<string, string> Meta_Data { get; set; }
    public Dictionary<string, TimeSeries> Lhocv { get; set; }
}

public class TimeSeries
{
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    public double Volume { get; set; }
}

Thanks!!!

King Coffee
  • 47
  • 4
  • 9
  • You can write a static DbInitializer class and call it on from Startup.cs or Program.cs. – Dennis VW Sep 20 '19 at 20:57
  • Populate with what? There are plenty examples of seeding a database. If you can't find any examples it's probably because you won't find any code using `Dictionary` navigation properties, simply because they're not supported. – Gert Arnold Sep 20 '19 at 21:15
  • I'm tried to do summing like: https://stackoverflow.com/questions/14779740/can-i-embed-an-object-in-an-ef-entity-serialize-on-save-deserialize-on-access but have Dbcontext do the serializing and deserializing and create a table if need be. – King Coffee Sep 20 '19 at 22:14
  • It appears the class object is the best place to serialization as given in the above. – King Coffee Sep 20 '19 at 22:29

1 Answers1

0

You can seed a database in many ways. Usually, you want it to have happened on startup. So you create a DbInitializer.cs class that has a static initialize method.

public static void Initialize(MyDbContext context)
{
    context.Database.EnsureCreated();

    // Create the objects you want to insert into DbContext.
    // Write it to a variable, for example, "var ExampleData".

    // Add example data.
    context.FiveMinStockHistory.Add(ExampleData)
    context.SaveChanges();
}

Then you could just run it on startup:


    public void Configure(IApplicationBuilder app, MyDbContext context)
    {
        MyDatabaseInitializer.Initialize(context);
    }

Easy peasy. Good luck!

Dennis VW
  • 2,977
  • 1
  • 15
  • 36