16

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?

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Filip Ekberg But if I connect to an existing database, I don't need to add model classes, do I?
@Srcee, no you are never required to add model classes, but it simplifies things a bit in the end.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.