Using EF “Code First” with an Existing Database
page 10 of 15
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 51760/ 150

Step 5: Configuring our Database Connection String

We’ve written all of the code we need to write to define our model layer.  Our last step before we use it will be to setup a connection-string that connects it with our database.

In my initial EF “code first” blog post I discussed a cool option that EF “code first” provides that allows you to have it auto-create/recreate your database schema for you.  This is a option that can be particularly useful for green-field development scenarios – since it allows you to focus on your model layer early in the project without having to spend time on updating your database schema after each model change.

Importantly, though, the auto-create database option is just an option – it is definitely not required.  If you point your connection-string at an existing database then EF “code first” will not try and create one automatically. The auto-recreate option also won’t be enabled unless you explicitly want EF to do this – so you don’t need to worry about it dropping and recreating your database unless you’ve explicitly indicated you want it to do so.

For this blog post we will not auto-create the database.  Instead, we’ll point at the existing Northwind database we already have.  To do this we’ll add a “Northwind” connection-string to our web.config file like so:

  <connectionStrings>
     <add name="Northwind" 
          connectionString="data source=.\SQLEXPRESS;Integrated
 Security=SSPI;AttachDBFilename=|DataDirectory|\northwind.mdf;User Instance=true" 
          providerName="System.Data.SqlClient" />
   </connectionStrings>

EF “code first” uses a convention where context classes by default look for a connection-string that has the same name as the context class.  Because our context class is called “Northwind” it by default looks for a “Northwind” connection-string to use.  Above our Northwind connection-string is configured to use a local SQL Express database.  You can alternatively point it at a remote SQL Server.


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 9:27:42 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search