Welcome Guest Search | Active Topics | Log In | Register

LINQ to SQL Options · View
paedotnet
#1 Posted : Monday, December 24, 2007 9:54:56 PM
Rank: ฝ่ามืออรหัน
มงกุฎทอง: ขอบคุณมากครับ สำหรับการแบ่งปันความรู้ให้กับสังคม
Groups: Administration

Joined: 12/6/2007
Posts: 582

การใช้งาน LINQ to SQL
LINQ to SQL จะประกอบไปด้วยสามส่วนคือ

Entity Class
Data Context
LINQ Query

เอาละครับเรามาเริ่มเขียนโปรแกรมจัดการกับฐานข้อมูลโดยใช้ LINQ กัน
เปิด Visual Studio 2008 ขึ้น (ถ้าใช้ Visual Studio 2005 จะต้องไป Download Linq มาติดตั้งก่อนนะครับ)
หลังจากเปิดขึ้นมาแล้วไปที่ File->New->Project->Visual c#->Console Application ให้ตั้งชื่อโปรเจคแล้วกด Ok
ฐานข้อมูลผมใช้ Northwind นะครับ


จากนั้นจะเข้าสู่หน้า Program.cs
ซึ่งมีโค้ดถูกสร้างขึ้นมาดังนี้

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestLinq1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

 

หลังจากนั้นให้ไป Add Reference ก่อนไปที่ชื่อโปรเจค คลิกขวาเลือก Add Reference... ในแถบที่ชื่อว่า .NET ให้เลือก
System.Data.Linq และ System.Xml.Linq
หลังจากนั้นตรงที่ประกาศ using ต่างๆให้เพิ่ม using System.Data.Linq; และ System.Xml.Linq; และ System.Data.Linq.Mapping;
(สำหรับ visual studio 2005 จะต้อง add System.Data.DLinq; , System.Data.Extensions; , System.Query; )

ตัวอย่างโค้ด

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
[Table(Name = "Customers")]
public class Customer
{
    [Column()]
    public string CustomerID;
    [Column()]
    public string companyname;
    [Column()]
    public string city;
    [Column()]
    public string country;
    public static void Main()
    {
        string constr = "Server =.;Database = northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Customer> customers = db.GetTable<Customer>();
        var q = from c in customers select c; //สร้างคำสั่ง select
        foreach (var t in q)
        {
            Console.WriteLine("{0} {1} {2} {3}", t.CustomerID, t.companyname, t.city, t.country);//แสดงผล
        }
        Console.ReadLine();
     }
}
 
 

 

คำอธิบาย
ตรง [Table(Name = "Customers")]  Table เป็น Attribute ซึ่งมี property คือ Name โดย Name นี้ใช้กำหนดชื่อของตารางในฐานข้อมูลที่ต้องการเช่น customers ถ้าไม่มี Name เช่น [Table()] ทางโปรแกรมจะไปใช้ชื่อของคลาสแทน


[Column()]
public string CustomerID; ตรงคำสั่ง [Column()] จะทำหน้าที่ Mapping ระหว่าง ฟิลด์ที่เรากำหนดด้านล่าง(public string CustomerID) กับ ฟิลด์ที่ชื่อ CustomerID ในฐานข้อมูล

DataContext ทำหน้าที่รับข้อมูลจาก Database ในแต่ละตารางในฐานข้อมูลถูกแสดงด้วย Table ซึ่งสามารถเข้าถึงสมาชิกในแต่ละฟิลด์ในตารางด้วยการใช้ GetTable


การใช้ Where เพื่อกำหนดเงื่อนไขการ Query

using System;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Collections.Generic;
[Table(Name = "Shippers")]//กำหนดตารางชื่อ Shippers
public class Shipper
{
    [Column()]
    public int shipperid;
    [Column()]
    public string companyname;
    [Column()]
    public string phone;
    public static void Main()
    {
        string constr = "Server =(local);Database = Northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Shipper> shippers = db.GetTable<Shipper>();
        var q = from c in shippers where c.companyname == "Federal Shipping" select c;
        foreach (var a in q)
        {
            Console.WriteLine("show  {0}\t{1}\t{2}", a.shipperid, a.companyname, a.phone);
        }
        Console.ReadLine();
    }
}


ผลลัพธ์แสดงดังรูป


 

ในการแสดงผลส่วน
 foreach (var a in q)
        {
            Console.WriteLine("show  {0}\t{1}\t{2}", a.shipperid, a.companyname, a.phone);
        }
เราสามารถใช้ชื่อคลาสแทนได้ดังนี้

  foreach (Shipper s in q)
        {
            Console.WriteLine(s.shipperid+"     "+s.companyname+"      "+s.phone);
        }


การใช้ select new

 

using System;
using System.Linq;
using System.Xml.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Collections.Generic;
[Table(Name = "Shippers")]//กำหนดตารางชื่อ Shippers
public class Shipper
{
    [Column()]
    public int shipperid;
    [Column()]
    public string companyname;
    [Column()]
    public string phone;
    public static void Main()
    {
        string constr = "Server =(local);Database = Northwind;Integrated Security =SSPI";
        DataContext db = new DataContext(constr);
        Table<Shipper> shippers = db.GetTable<Shipper>();
        var d = from c in shippers where c.companyname == "Federal Shipping" select new { c.phone, c.shipperid };
        foreach (var g in d)
        {
            Console.WriteLine(g.phone+"      "+g.shipperid);
        }
        Console.ReadLine();
    }
}
 

 

 

E-Mail / MSN : paedotnet@hotmail.com
paedotnet
#2 Posted : Sunday, December 30, 2007 5:08:05 PM
Rank: ฝ่ามืออรหัน
มงกุฎทอง: ขอบคุณมากครับ สำหรับการแบ่งปันความรู้ให้กับสังคม
Groups: Administration

Joined: 12/6/2007
Posts: 582

LINQ

LINQ มี 5 แบบคือ

LINQ to Object
LINQ to XML
LINQ to DataSet
LINQ to SQL
LINQ to Entities

 Query Operator ใน LINQ มีหลายชนิดเช่น Select,Where,Join,GroupBy,OrderBy,ThenBy,OrderByDescending,ThenByDescending,Cast,GroupJoin,SelectMany

ตัวอย่างการ ใช้งาน Select เพื่อแสดงข้อมูลในตัวแปร array

using System;
using System.Linq;
public class TestLINQ
{
    public static void Main()
    {
        string[] str = { "one","two","three","four","five" };
        var q = from s in str select s;
        foreach (var a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
one
two
three
four
five

การ ใช้ where เพื่อกำหนดเงื่อนไข

using System;
using System.Linq;
public class TestLINQ
{
    public static void Main()
    {
        string[] str = {"one","two","three","four","five"};
        var q =from s in str where s.Length < 4 select s; //ใช้ where เพื่อกำหนดเงื่อนไขวเพื่อให้แสดงสมาชิกที่มีความยาวน้อยว่า 4
        foreach (var a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}
 
 
 
 
ผลลัพธ์
one
two
คำอธิบายที่ได้ one และ two เพราะตรงตามเงื่อนไขที่มีความยาวของตัวอักษรน้อยกว่า 4 (where s.Length <4)


การใช้งาน OfType

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "A", "B", "C" };
        IEnumerable<string> i = str.OfType<string>();
        foreach (string n in i)
        {
            Console.WriteLine(n);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
A
B
C

การใช้งาน OrderBy


using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = from s in str where s.Length == 3 orderby s select s;
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}


ผลลัพธ์จะได้
One
Six
Two
ในตัวอย่างนี้จะเป็นการเลือก สมาชิกในตัวแปร str ที่มีขนาดความยาวตัวอักษรเท่ากับ 3 โดยเรียงลำดับตัวอักษรจาก (a-z)


ตัวอย่างการใช้ where เพื่อเลือกข้อมูลที่มีขนาดความยาวตัวอักษรเท่ากับ 3

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = str.Where(s => s.Length == 3);
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}
 
 
 
ผลลัพธ์จะได้

Two
Six
One


การแสดงข้อความตามเงื่อนไขที่กำหนด

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = {"Two","Six","Three","four","five","One"};
        IEnumerable<string> i = str.Where(s => s[0] == 'T');
        foreach (string a in i)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}

 

ผลลัพธ์จะได้
Two
Three
คำอธิบายในตัวอย่างนี้ได้มีเงื่อนไขคือ where(s=>s[0] =='T') หมายถึง ให้เลือกสมาชิกที่ขึ้นต้นด้วยตัวอักษร T ซึ่งในสมาชิกของตัวแปร str จะมีสมาชิกที่ขึ้นต้นด้วยตัว T มี สองสมาชิกคือ Two,Three

 


การใช้งาน  Group

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "Ant", "Hourse", "Zebra", "Bird", "Dog" };
        var q = from s in str orderby s group s by s.Length into mygroups orderby mygroups.Key  select new {Animal = mygroups };
        foreach (var a in q)
        {
            foreach (string s in a.Animal)
            {
                Console.WriteLine(s);
            }
        }
      
        Console.ReadLine();
    }
}

 

การใช้ SelectMany

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        string[] str = { "1 A B C","2 D E F","3 G H T"};
        var q = str.SelectMany(s => s.Split(' '));
        foreach (string a in q)
        {
            Console.WriteLine(a);
        }
        Console.ReadLine();
    }
}


ตัวอย่างการแสดงชนิดของสมาชิกใน array

using System;
using System.Linq;
public class TestLamda
{
    public static void Main()
    {
        object[] obj = { 1, "A", 2, "B", 3, "C" };
        var q = obj.Select(o => o.GetType().Name).OrderBy(o => o);
        foreach (object o in q)
        {
            Console.WriteLine(o);
        }
        Console.ReadLine();
    }
}


LINQ to XML

ตัวอย่าง

using System;
using System.Linq;
using System.Xml.Linq;
public class TestLINQ
{
    public static void Main()
    {
        var animals = new[] { new { Name = "puppy", Color = "Brown" }, new { Name = "doppy", Color = "White" }, new { Name = "bamby", Color = "Black" } };
        XElement x = new XElement("animals", from a in animals select new XElement("animal", new XAttribute("Name", a.Name), new XAttribute("Color", a.Color)));
        Console.WriteLine(x);
        Console.ReadLine();
     }
}
E-Mail / MSN : paedotnet@hotmail.com
noOTOon
#3 Posted : Thursday, January 17, 2008 5:38:18 PM
Rank: มือฝึกหัด

Groups: Member

Joined: 1/17/2008
Posts: 1

ถ้าใช้ vs 2005 ต้อง download Linq มาติดตั้งก่อนเนี่ยม่ายถึง framework 3.5 อะเปล่าค่ะถ้าม่ายช่าย

แล้วมันต้องทำยังงัยอะค่ะ vs 2005 ถึงจะให้ได้อะ..

ช่วยด้วยนะค่ะ ..ขอบคุณค่ะ..

paedotnet
#4 Posted : Friday, January 18, 2008 1:27:13 PM
Rank: ฝ่ามืออรหัน
มงกุฎทอง: ขอบคุณมากครับ สำหรับการแบ่งปันความรู้ให้กับสังคม
Groups: Administration

Joined: 12/6/2007
Posts: 582

สำหรับถ้าจะใช้ Linq ใน VS 2005 ต้อง download  : LINQ Preview (May 2006). มาติดตั้งครับ ส่วน .net framework 3.5 จะติดตั้งหรือไม่ก็ได้ ( เฉพาะใน VS 2005 นะครับถ้าเป็น        VS 2008 จะมี .net framework 3.5 ติดตั้งมาให้อยู่แล้ว )

สามารถdownload LINQ สำหรับ VS 2005  ได้ที่ http://www.microsoft.com  หรือจะเข้าไปที่หน้า download เลยก็ได้ ที่ http://www.microsoft.com/downloads/details.aspx?FamilyID=1e902c21-340c-4d13-9f04-70eb5e3dceea&DisplayLang=en

E-Mail / MSN : paedotnet@hotmail.com
noOTOon
#5 Posted : Tuesday, January 22, 2008 10:55:58 AM
Rank: มือฝึกหัด

Groups: Member

Joined: 1/17/2008
Posts: 1

เย้ เย้ ขอบคุณมากนะค่ะสำหรับคำตอบเด๋วจะลองเล่นดู...

Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Creative Commons License
CodeToday.NET is licensed under a Creative Commons Attribution-Noncommercial 3.0 Thailand License.
Based on a work at www.CodeToday.net.