Creating a Connection String and Working with SQL Server LocalDB

3.91 (11 votes)

This tutorial is the fifth in a series of a Visual Basic versions of the Introduction to ASP.NET MVC 5 tutorials published on the www.asp.net site. The original series, produced by Scott Guthrie (twitter @scottgu ), Scott Hanselman (twitter: @shanselman ), and Rick Anderson ( @RickAndMSFT ) was written using the C# language. My versions keep as close to the originals as possible, changing only the coding language. The narrative text is largely unchanged from the original and is used with permission from Microsoft.

This tutorial series will teach you the basics of building an ASP.NET MVC 5 Web application using Visual Studio 2013 and Visual Basic.  A Visual Studio Express For Web project with VB source code is available to accompany this series which you can download.

The tutorial series comprises 11 sections in total. They cover the basics of web development using the ASP.NET MVC framework and the Entity Framework for data access. They are intended to be followed sequentially as each section builds on the knowledge imparted in the previous sections. The navigation path through the series is as follows:

  1. Getting Started
  2. Adding a Controller
  3. Adding a View
  4. Adding a Model
  5. Creating a Connection String and Working with SQL Server LocalDB
  6. Accessing Your Model's Data from a Controller
  7. Examining the Edit Methods and Edit View
  8. Adding Search
  9. Adding a New Field
  10. Adding Validation
  11. Examining the Details and Delete Methods

5. Creating a Connection String and Working with SQL Server LocalDB

The MovieDBContext class you created in the previous section handles the task of connecting to the database and mapping Movie objects to database  records. One question you might ask, though, is how to specify which database it will connect to. You don't actually have to specify which database to use,  Entity Framework will default to using  LocalDB. In this section we'll explicitly add a connection string in the Web.config file of the application.

SQL Server Express LocalDB

LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to  work with databases as .mdf files. Typically, LocalDB database files are kept in the App_Data folder of a web project.

SQL Server Express is not recommended for use in production web applications. LocalDB in particular should not be used for production with a web application because it is not designed to work with IIS. However, a LocalDB database can be easily migrated to SQL Server or SQL Azure.

In Visual Studio 2013 (and in 2012), LocalDB is one of the components that comprises the default installation of Visual Studio or Visual Studio Express.

By default, the Entity Framework looks in the web.config file for a connection string named the same as the object context class (MovieDBContext for this project).  For more  information see  SQL Server Connection Strings for ASP.NET Web Applications.

Open the application root Web.config file shown below. (Not the Web.config file in the Views folder.)

Adding a connection string

Find  the <connectionStrings>  element:

Adding a connection string

Add the following connection string to the <connectionStrings>  element in the Web.config file.

<add name="MovieDBContext"
     connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
     providerName="System.Data.SqlClient" />

The following example shows a portion of the Web.config file with  the new connection string added:

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20140425082247.mdf;Initial Catalog=aspnet-MvcMovie-20140425082247;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

The two connection strings are very similar. The first connection string is  named DefaultConnection and is used for the membership database to control who can access the application. The connection string you've added specifies a LocalDB database named Movie.mdf located in the App_Data  folder.  We won't use the membership database in this tutorial, for more information on membership, authentication and security, see Rick Anderson's tutorial Deploy a Secure ASP.NET MVC app with Membership, OAuth, and SQL Database to a  Windows Azure Web Site.

The name of the connection string must match the name of the DbContext class.

Imports System.Data.Entity

Namespace Models
    Public Class Movie
        Public Property ID As Integer
        Public Property Title As String
        Public Property ReleaseDate As DateTime
        Public Property Genre As String
        Public Property Price As Decimal
    End Class

    Public Class MovieDbContext
        Inherits DbContext

        Public Property Movies As DbSet(Of Movie)
    End Class

End Namespace

You don't actually need to add the MovieDBContext connection string. If you don't specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class (in this case MvcMovie.Models.MovieDBContext). You can name the database anything you like, as long as it has the .mdf  suffix. For example, we could name the database MyFilms.mdf.

Next, you'll build a new MoviesController class that you can use  to display the movie data and allow users to create new movie listings.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 155358

9 Comments

- Evita

Hi Mike,

Thank you so much for the tutorial. It really help me.
However, I am a bit confuse about .mdf and got an error Entity Type has no key defined. I've build again my solution but it is still not working

- Mike

@Evita,

That error means that Entity Framework could not find a property on your model that can be used as a primary key. EF requires a key to be an integer or Guid and named "ID" or [entityname]ID e.g. MovieID. You can name it something else, but if you do, you must add the <Key> attribute to the property:


<Key>
Public Property MyKey As Integer

- Benjamin

Hi Mike, great article. I am learning a lot. As commented @Evita, the <Key> Data Annotation is mandatory for the automatic code generation, I think that this part needs to be added to the tutorial.

- Mike

@Benjamin,

As I said to Evita, the <Key> DataAnnotation is only mandatory if you name your Key property in such as way that Entity Framework cannot identify it via convention.

This series is intended to introduce MVC 5 using VB, so Entity Framework is not the real focus. There is another series that looks much more closely at EF here: http://www.mikesdotnetting.com/article/241/mvc-5-with-ef-6-in-visual-basic-creating-an-entity-framework-data-model

- Ervis

Great tutorial.

I do have a probem though, nothing is happening in my App_Data and I can't understand why. I've tried altering the connectionstring, but it never happens. The data is visible in the browser, and the connection seems to work.

- Hutchy

Within Movie.vb you have the Public Class named "MovieDbContext" but in Web.config you have it as "MovieDBContext" one has a capital for the B the other doesn't.

- Mike

@Hutchy

VB is case insensitive.

- Keith

As always worst explanation, but this time you rocked with plagiarism too .. huhh.. copied from Rick Anderson article.
I am not sure why you show others that you are more knowledgeable than them when you are copying from others. Shame.

- Mike

Hi "Keith",

If you had taken the trouble to read the first paragraph, you might have noticed that I haven't plagiarised anything. I volunteered freely and in my own time to provide VB translations of some of the MVC articles posted on the ASP.NET site. The text of the article is used with the full permission of Microsoft, arranged for me by Rick Anderson.

Perhaps next time you'll attempt to establish some facts before posting troll comments. In the meantime, perhaps you could point us all in the direction of your community contributions?

No? Didn't think so. Shame.

Recent Comments

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...