Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Monday, October 13, 2008

LinQ to SQL (union with multiple fields)

Description:

This example demonstrate how to perform union on two tables using multiple fields.

Example:
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
{
static void Main(string[] args)
{
UnionExample();
Console.Read();
}

public static void UnionExample()
{
using (NorthwindDataContext db = new NorthwindDataContext())
{
List<Person> persons = db.Customers
.Select(c => new Person { PersonName = c.ContactName,CountryName= c.Country})
.Union(db.Employees
.Select(c => new Person { PersonName = c.FirstName, CountryName = c.Country}))
.ToList<Person>();

foreach (Person person in persons)
{
Console.WriteLine(person.PersonName + "\t" + person.CountryName);
}
}
}
}

class Person
{
private string personName;
private string countryName;

public string PersonName
{
get { return personName; }
set { personName = value; }
}

public string CountryName
{
get { return countryName; }
set { countryName = value;}
}
}
}

Friday, October 10, 2008

LinQ to SQL basic sample

Description:
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;
}
}