+92 332 4229 857 99ProjectIdeas@Gmail.com

How to get the data from table through ID or Name (LINQ To SQL)

Getting the data from table through ID or Name
In the previous "how to get all data from table" post, we showed the whole customers from the table, here we would mention an ID or Name to get the data against it.

This is the connection string which let you connect to the server: 
·        Data Source = "Your Server Name"
·        Initial Catalog = "The name of your database"
·        Integrated Security = "true" for getting your credentials automatic to your current login account in windows, in this way you don't have to use user id and password while establishing connection with SQL server. 
static string conString = @"Data Source = MOAVIA_OSAMA-PC\SQLEXPRESS;Initial Catalog=MyFirst;Integrated Security=true"; 
The following is the class generated when you add "Linq to SQL classes" to project, which takes an argument of connection string:
DataClassesDataContext dc = new DataClassesDataContext(conString);

Query 1 : Getting data through specifying Name of a Customer:
 The following query is a simple query which gets all the data from Customer table against the name "Bilal": 
 var query1 = from Customer c in dc.Customers
                  where c.Name.Equals("Bilal")  // Name = Bilal to get his data only
                  select c;
can also use .Contains() function instead of .Equals() function in above where clause.
  foreach (var item in query1)
     Console.WriteLine(item.ID + " " + item.Name + " " + item.Address);

Query 2 : Getting data through specifying ID of a Customer:
var query2 =
      from Customer c in dc.Customers
      where c.ID == 4 // ID = 4 to get his data only
      select c;

  foreach (var item in query2)
    Console.WriteLine(item.ID + " " + item.Name + " " + item.Address);