Entity-Framework Code First Designer with Database Initialization in few simple steps!

11/05/2012

I find it very frustrating that I cannot use the entity model designer to generate code-first DbContext & entities that retains all the aspects of code-first including database initialization.

Here are a set of instructions that can easily help you to achieve true code-first using the EDM designer, and allowing initialization of database (database initialization is not supported in model-first, it only allows generation of database scripts that has to be generated on the server).

This is very useful in small projects where you don’t want to mess with the database, and you rather it being generated automatically.

In my example I chose to use SQL Compact Edition, but you can use SQL Express or other as well.

  1. Right-click the project and select “Add New Item”
  2. Select ADO.NET Entity Data Model, and rename the class if necessary
  3. Choose “Empty Model” when asked
  4. RIght-click the designer surface and click “Add Code Generation Item…”
  5. From the left menu select “Online Templates” then under category “Database” choose EF 4.x DbContext Generator for C# (or different lang.)
  6. Two new template files (*.tt) were generated to the project, open the Context.Context.tt file (the first ‘Context’ should be your model name)
  7. Search for the constructor template, it calls the base constructor:
    : base(“name=<#=container.Name#>)
    Remove the
    name= from it so it remains : base(<#=container.Name#>)
  8. Erease or comment the OnModelCreating method
  9. Add the following lines to your bootstrapper or App_Startup or any point where the application initializes:
    AppDomain.CurrentDomain.SetData("DataDirectory", Environment.CurrentDirectory);
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ContextContainer>());
    

     

If it’s not a web application you’re dealing with, you will need to set the DataDirectory variable of the generated connection string, see the first line above.

The second line sets the default connection factory which is the pipe Entity-Framework uses to generate a connection string (and hence a database), you can use either SqlCeConnectionFactory like in the above example, or SqlConnectionFactory and you can even create your own connection factory by implementing IDbConnectionFactory.

You can change the third line by setting the DatabaseInitializer to your own by deriving from the class above (you can use any class that implement IDatabaseInitializer), and override the Seed method, which allows you setting initial database values like deafult username/password etc.

Here is the sample project’s execution, it will automatically generate an sdf database file that will be filled with data with no hassle of servers and all that. In fact you don’t even care what the database schema looks like.

class Program
{
  public static void Main(string[] args)
  {
    AppDomain.CurrentDomain.SetData("DataDirectory", Environment.CurrentDirectory);
    Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ContextContainer>());
 
    using (var context = new ContextContainer())
    {
      context.Contacts.Add(new Contact { FirstName = "asdf" });
      context.SaveChanges();
    }
  }
}

As you can see, it generated the database file to the project’s folder, no database or schema mentioned at all.

Hope this helps, please comment on for questions.

Shimmy

After following the directions above, you can use the database

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

11 comments

  1. Air Conditioner11/05/2012 ב 17:54

    Many thanks for a good time visiting your web blog. I am highly pleased and right now an aficionado. Make sure you update this again soon. Cheers!

    Reply
  2. Paul27/07/2012 ב 06:22

    I have learn several good stuff here. Certainly worth bookmarking for revisiting.
    I wonder how a lot attempt you put to make the sort of magnificent informative web site.

    Reply
  3. Slater11/08/2012 ב 19:54

    Yes! Finally someone writes about lose weight.

    Reply
  4. fat burning11/10/2012 ב 17:43

    Muchos Gracias for your blog post.Really looking forward to read more. Will read on

    Reply
  5. Reedy18/10/2012 ב 07:18

    Very good post. I am experiencing many of these issues as well.
    .

    Reply
  6. Somerville08/11/2012 ב 11:13

    What’s up, I desire to subscribe for this web site to take hottest updates, thus where can i do it please help.

    Reply
  7. Shimmy08/11/2012 ב 15:59

    @Somerville
    Go to http://goo.gl/2C4aY and choose one of the subscription options.
    I personally use Google Reader to subscribe to RSS feeds.

    Reply
  8. Hays28/11/2012 ב 18:59

    I got this web page from my friend who told me on the topic of this website and now this time I am
    visiting this site and reading very informative articles or reviews here.

    Reply
  9. Engle02/12/2012 ב 04:59

    It’s difficult to find experienced people for this topic, but you seem like you know what you’re talking about!

    Thanks

    Reply
  10. Haines02/12/2012 ב 05:07

    Thanks for sharing your thoughts about .Net. Regards

    Reply
  11. Harris10/12/2012 ב 06:52

    It’s going to be end of mine day, but before finish I am reading this great article to improve my know-how.

    Reply