Entity Framework Inserting Initial Data On Rebuild

后端 未结 1 1158

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

I\'ve defined ContactType.cs as follows:

public class ContactType
{
            


        
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 11:30

    You create a custom database initializer and overwrite the Seed method

    public class MyContextInitializer
        : DropCreateDatabaseIfModelChanges
    {
        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 context MyContext:

    Database.SetInitializer(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 into a static constructor of your context to make sure that the intializer is set before you create the first context instance:

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

    Instead of the base initializer DropCreateDatabaseIfModelChanges you can also derive from DropCreateDatabaseAlways or CreateDatabaseIfNotExists if that better meets your needs.

    0 讨论(0)
提交回复
热议问题