Entity Framework Insert source data during rebuild

I am using Entity Framework code - first with a MySQL data source.

I defined ContactType.cs as follows:

 public class ContactType { [Key] public int ContactTypeId { get; set; } [Required, StringLength(30)] public string DisplayName { get; set; } } 

My question is, after I rebuild the database, how can I create an EF to insert (without SQL) some types of contacts into the database. Usually, the database is rebuilt as an empty diagram, but I would like to add such types of contacts as (Home, Mobile, Office, Fax).

+6
source share
1 answer

You create a custom database initializer and overwrite the Seed method

 public class MyContextInitializer : DropCreateDatabaseIfModelChanges<MyContext> { protected override void Seed(MyContext context) { context.ContactTypes.Add(new ContactType { DisplayName = "Home" }); context.ContactTypes.Add(new ContactType { DisplayName = "Mobile" }); context.ContactTypes.Add(new ContactType { DisplayName = "Office" }); context.ContactTypes.Add(new ContactType { DisplayName = "Fax" }); //EF will call SaveChanges itself } } 

Then you register this initializer for your derived MyContext context:

 Database.SetInitializer<MyContext>(new MyContextInitializer()); 

This is a static method of the Database class and should be called somewhere once at application startup. You can also put it in the static constructor of your context to make sure that the intializer is set before creating the first instance of the context:

 static MyContext() { Database.SetInitializer<MyContext>(new MyContextInitializer()); } 

Instead of the basic DropCreateDatabaseIfModelChanges<T> initializer, you can also get from DropCreateDatabaseAlways<T> or CreateDatabaseIfNotExists<T> if that suits your needs better.

+15
source

Source: https://habr.com/ru/post/898415/


All Articles