C# – Linq – how to connect to a database

.net-4.0clinq

I have created a database with Microsoft SQL Server Management Studio (Microsoft SQL Server 2008).
I've been searching around but either I don't understand it or can't find it, but how do I connect from within my project (Visual Studio 2010 Enterprise) so that I can send and receive data from the DB?
My database name is MyDB.

var database = new MyDB();

In Solution Explorer, right-click References, and then click Add Reference.

In the Add Reference dialog box, click .NET, click the System.Data.Linq assembly, and then click OK.

The assembly is added to the project.

Add the following directives at the top of Program.cs:

Best Answer

The easiest way to add the ability to have an app communicate with a SQL Server database is to use LINQ to SQL. Assuming you've already made a database connection in the Server Explorer pane, then:

  1. Add a new item to the project and choose teh LINQ to SQL Classes template
  2. Enter an appropriate name (default is DataClasses1.dbml) and click add. The name you choose will also be used to create the class name of the DataContext by appending "DataContext" to the name you choose (e.g., Test.dbml is the filename and TestDataContext will be the classname.)
  3. Then, from the Server Explorer window, drag the tables that you want to use into the dbml file that you created in step 2.
  4. Search the web for resources on using LinqToSQL (my suggestion is to start with ScottGu's blog at http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx)

Caveat: While this is the arguably the simplest way to get quick connectivity to a database, there are others that will have better performance and/or features like nHibernate or Microsoft's Entity Framework as Coding Gorilla also suggested.