I am using Entity Framework code-first with a MySQL data source.
I’ve 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 have EF to insert (without SQL) some contact types into the database. Normally, the DB is rebuilt as a blank schema, but I’d like to add contact types like (Home,Mobile,Office,Fax).
You create a custom database initializer and overwrite the
SeedmethodThen you register this initializer for your derived context
MyContext:This is a static method of the
Databaseclass 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:Instead of the base initializer
DropCreateDatabaseIfModelChanges<T>you can also derive fromDropCreateDatabaseAlways<T>orCreateDatabaseIfNotExists<T>if that better meets your needs.