On Rebuild, Entity Framework Inserts Initial Data

c# entity-framework mysql

Question

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).

1
6
7/13/2016 4:42:07 AM

Accepted 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 context MyContext:

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 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<MyContext>(new MyContextInitializer());
}

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

17
9/30/2011 10:33:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow