Steps to describe How to use linq for the first time in dotnet C# using VS2008

Guide to use linq with windows application in dot net. Step by step process to use linq and configure the database connection in linq to point it to config file.

Below are the detailed step which will be useful for a beginner to Linq.
1.Open visual studio 2010.Go to the menu File->New->Project->Windows Forms Application and give a name as MyFirstLinqProject.Click on ok. A new form will be created.

2.Now right click on your project (MyFirstLinqProject) and click Add->New Item->Linq to Sql classes. Give a name of your database table. In my case i have created a database called MyDatabase and a table called Persons. So i will name it like 'Persons.dbml'. Click on add.A blank dbml file is shown on the screen.

3.Create a new Data Connection in the Server Explorer pointing to your database(MyDatabase).

4.Expand your database and drag your table(persons) into the dbml file. Notice that the name of the data table has changed(person) and all the columns in the database table has been added.

5. Now to point the dbml to our config file the first thing that we have to do is
Right click on the dbml file (where u have dragged the data table) go to properties->Connection. Expand connection and change application settings to false.

6. Now if you notice the Persons.designer file there will be this line of code

public PersonsDataContext() : base("Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True", mappingSource)

Delete these lines of code because the connection string is hard coded there.

7. Open the solution explorer , right click on the dbml(Persons.dbml) and say view code.
A .cs file (Person.cs) will be created . Here we have to give the exact connection string and point it to config file like shown below.

public PersonsDataContext() :base(global::System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ToString(), mappingSource)

Note: We may have to add System.Configuration reference to our project.
MyDatabaseConnectionString is the name of my connection string that is present in config file.

Now we are all set to use linq to sql to get results from the database tables.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: