LINQ to SQL Step-By-Step Example

1 comment

The first step in building a LINQ to SQL application is declaring the classes we will use to represent your application data:

In our simple example, we’ll define a class named Contact and associate it with the Contacts table of the Northwind sample database provided by Microsoft with the LINQ code samples.
[Table(Name="Contacts")]
class Contact
{
public int ContactID;
public string Name;
public string City;
}

In addition to associating entity classes with tables, we need to denote each field or property we intend to associate with a column of the table.
[Table(Name="Contacts")]
class Contact
{
[Column(IsPrimaryKey=true)]
public int ContactID { get; set; }
[Column(Name="ContactName"]
public string Name { get; set; }
[Column]
public string City { get; set; }
}

The next thing we need to prepare before being able to use language-integrated queries is a System.Data.Linq.DataContext object. The purpose of DataContext is to translate requests for objects into SQL queries made against the database and then assemble objects out of the results.

The DataContext object looks like this:
string path = Path.GetFullPath(@"..\..\..\..\Data\northwnd.mdf");
DataContext db = new DataContext(path);

The DataContext provides access to the tables in the database. Here is how to get access to the Contacts table mapped to our Contact class:
Table<Contact> contacts = db.GetTable<Contact>();

LINQ to SQL complete source code
using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
static class HelloLinqToSql
{
[Table(Name="Contacts")]
class Contact
{
[Column(IsPrimaryKey=true)]
public int ContactID { get; set; }
[Column(Name="ContactName")]
public string Name { get; set; }
[Column]
public string City { get; set; }
}
static void Main()
{
string path =
System.IO.Path.GetFullPath(@"..\..\..\..\Data\northwnd.mdf");
DataContext db = new DataContext(path);
var contacts =
from contact in db.GetTable<Contact>()
where contact.City == "Paris"
select contact;
foreach (var contact in contacts)
Console.WriteLine("Bonjour "+contact.Name);
}
}


1 comment:

  1. NICE PROGRAM
    VISIT MY SITE
    http://stuffuser.blogspot.in/

    ReplyDelete