DCSIMG
Entity-Framework Code First Designer with Database Initialization in few simple steps! - Shimmy on .NET

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

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

Published Friday, May 11, 2012 6:49 AM by Shimmy

Comments

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

Friday, May 11, 2012 5:54 PM by Air Conditioner

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!

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

Friday, July 27, 2012 6:22 AM by Paul

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.

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

Saturday, August 11, 2012 7:54 PM by Slater

Yes! Finally someone writes about lose weight.

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

Thursday, October 11, 2012 5:43 PM by fat burning

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

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

Thursday, October 18, 2012 7:18 AM by Reedy

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

.

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

Thursday, November 08, 2012 11:13 AM by Somerville

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

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

Thursday, November 08, 2012 3:59 PM by Shimmy

@Somerville

Go to http://goo.gl/2C4aY and choose one of the subscription options.

I personally use Google Reader to subscribe to RSS feeds.

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

Wednesday, November 28, 2012 6:59 PM by Hays

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.

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

Sunday, December 02, 2012 4:59 AM by Engle

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

Thanks

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

Sunday, December 02, 2012 5:07 AM by Haines

Thanks for sharing your thoughts about .Net. Regards

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

Monday, December 10, 2012 6:52 AM by Harris

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

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems