Posted by : Sudhir Chekuri Tuesday, 27 October 2015

LINQ to SQL is also known as DLINQ. It is used to query data in SQL server database by using LINQ expressions.

Example:

Right click on data connections in server explorer.
Add connection -> enter servername, authentication, database name.
Test connection and click on ok.

Right click on your project in solution explorer
Click on Add item -> Add linq to Sql class(.dbml file) to your project

Open tables in new data connection added in server explorer and drag them to design view of linq to sql class.

Program in console application to display data from database:

using System;
using System.Linq;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            //You can see this context name in .dbml file in designer.cs class
            DataClasses1DataContext db = new DataClasses1DataContext("Data Source=.;Initial Catalog=stdntdb;Integrated Security=True");

            stdnttable newStdnt = new stdnttable();
            //Select command to retreive all rows from the table
            var q =
        from a in db.GetTable<stdnttable>()
        select a;
            //printing all rows of data
            foreach (var s in q)
            {
                Console.WriteLine("username: " + s.username + ", Password: " + s.pwrd);
            }

            //Select command with where condition to display names starting with sa
            Console.WriteLine("");
            var q1 =
       from a in db.GetTable<stdnttable>() where a.username.StartsWith("sa")
       select a;
            //printing all rows of data
            foreach (var s in q1)
            {
                Console.WriteLine("username: " + s.username + ", Password: " + s.pwrd);
            }

            Console.ReadKey();
        }
    }
}


Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -