1. This sample shows how to connect SQL Server 2005 Northwind sample database with LinQ DataContext.
2. How to extend built-in DataContext class and have your own Strongly Typed class.
3. Querying the database and finding employees whose name starts with alphabet 'A'.
Step 1:
Download Sample database from here :
http://code.msdn.microsoft.com/northwind/Release/ProjectReleases.aspx?ReleaseId=1401
Step 2:
Sample Console Application Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace LinQExamples
{
class Program
{
public static string connectionString
= "Data Source=localhost;Min Pool Size=50;Max Pool Size=200;Initial Catalog=Northwind;Integrated Security=True";
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext(connectionString);
var emps = db.Employees.Where(E => E.FirstName.StartsWith("A")).ToList();
foreach (Employees empoyee in emps)
{
Console.WriteLine(empoyee.FirstName + "\t" + empoyee.LastName);
}
}
}
public partial class NorthwindDataContext: DataContext
{
partial void OnCreated();
public const string defaultConnectionString
= "Data Source=localhost;Min Pool Size=50;Max Pool Size=200;Initial Catalog=Northwind;Integrated Security=True";
public System.Data.Linq.Table<Employees> Employees
{
get
{
return this.GetTable<Employees>();
}
}
public NorthwindDataContext(): base(defaultConnectionString)
{
OnCreated();
}
public NorthwindDataContext(string connectionString)
: base(connectionString)
{
OnCreated();
}
}
[Table(Name = "dbo.Employees")]
public class Employees
{
[Column]
public string FirstName;
[Column]
public string LastName;
}
}
No comments:
Post a Comment