Practical .NET

LocalDB: The Database Without a Connection String

If you just want to get going with a code-first database, you don't even need to define a connection string -- just write your objects.

After you install Entity Framework in your application, if you look at the bottom of your application's config file you should find this element (or something very much like it):

<entityFramework>
  <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, 
    EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" 
        type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

If you're working in a code-first mode, this element eliminates the need for you to define a database and create a connection string for your DbContext object. Instead, the first time you access your data, Entity Framework will create your database for you, using LocalDB as your database engine (assuming you're using Visual Studio 2012 or later).

After you run your application and Entity Framework has created your database, you can find its MDF file in your application's App_Data folder (you may have to turn on Show All Files at the top of Solution Explorer and click the Refresh button to see it). Double-clicking that database file will open it in Server Explorer.

A couple of caveats. First, for this to work, I sometimes have to manually start LocalDB. To do that, open a command prompt and type:

SqlLocalDB start

If you open your connection to the database in Server Explorer, you may also need to close that connection before debugging, or your application will stop with a "database already in use by another user" error. Just right-click on your connection in Server Explorer and select Close to close the connection.

Of course, in the long run, you'll want to set up a connection string that points to your production database and tie your DbContext object to that connection string. As a starting point, there's nothing stopping you from selecting your database's connection in Server Explorer, copying the connection string from the Properties List and pasting it into your config file inside a well-formed connectionStrings element (don't forget to give your connection string the same name as your DbContext object). Later, you can swap in your production connection string.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube