How can I seed a database with static data using the Entity Framework?

How can I create (seed) a lot of static data in the Entity Framework? By static data, I mean data that is in the database, but exists only once.

For example, in my database I have a CountrySet containing all countries of the world. I would like these countries to always be there, but the fact is that every time I destroy my database and recreate it for a new deployment, all this data is lost.

Creating all this when my application starts up (if it has not already been created) seems to be very time sensitive.

What can i do here?

+3
source share
2 answers

:

Seed, , Initializer?

:

- :

System.Data.Entity.Database.SetInitializer(new SystemContext.SystemInitializer());

SystemContext - DbContext .

- :

public class SystemContext : DbContext
    {
        public DbSet<Stock> Stocks { get; set; }
        public DbSet<RawDayValues> StockRawValues { get; set; }

        public SystemContext()
            : base("Server=localhost;Database=test;Trusted_Connection=True;") 
        { }

        public class SystemInitializer : DropCreateDatabaseIfModelChanges<SystemContext>
        {
            #region SEED
            // This is what you're looking for!
            protected override void Seed(SystemContext context)
            {
                try
                {
                    var stock = new Stock() { Symbol = "TEST" };
                    context.Stocks.Add(stock);
                    context.SaveChanges();
                }
                catch (Exception ex) { Console.Error.WriteLine(ex.Message); }
                base.Seed(context);
            }

            #endregion
        }
    }

, .

, "" "" .

, - , , , , , .

, :)

: , , . , , . , /.

:)

+4

, :

System.Data.Entity.Database.SetInitializer<MyContext>(new MyInitializer());

"MyInitializer" - , IDatabaseInitializer<MyContext>. InitializeDatabase(TContext context), , ().

, db.

+1

All Articles