Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to an existing database in ASP.NET MVC?

I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the App_Data folder. I don't want to do this.

I'd like to create a new version of Nerd Dinner and move the connection string to the web.config, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.

What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?

like image 230
Mark Sandman Avatar asked Feb 11 '11 18:02

Mark Sandman


2 Answers

I always go to http://www.connectionstrings.com/ when I forget how a connectionstring is written.

Standard security SQL Server 2008

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Here is an article on MSDN talking about How to: Read Connection Strings from the Web.config.

You have a section almost at the top in your Web.config called connectionstrings, it could look something like this:

<connectionStrings>
  <add 
    name="NorthwindConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to ADO.NET Entity Framework here. But first of all you should focus on getting your connection up and running to your database using the information at the top.

like image 186
Filip Ekberg Avatar answered Sep 20 '22 16:09

Filip Ekberg


An additional way to have your context 'point' to the connextionsStrings line in the web.config file is to try this constructor.

public class MainDB : DbContext
{
    public MainDB() : base ("name=DefaultConnection")
    { 
    }

    public DbSet<User> Users { get; set;}
}

Then change the name to DefaultConnection in the web.config file.

like image 22
coding_is_fun Avatar answered Sep 23 '22 16:09

coding_is_fun