ASP.NET

29.ADO.NET - Linq To SQL

Godffs 2009. 9. 30. 20:11
반응형
Form1.Designer.cs

[그림29-1]


       private System.Windows.Forms.ListBox listBox1;


AddressBook.cs [ Class 파일 추가 ]
Linq를 사용하기 위해 참조추가를 합니다.

[그림29-2]


namespace WinLinqToSQL

{

    /// <summary>

    /// AddressBook 테이블과 일대일 매칭되는 클래스

    /// </summary>

    [Table(Name="AddressBook")] // Table 특성 사용해서 테이블로 보자

    public class AddressBook

    {

        private int _Num;

        [Column(IsPrimaryKey=true, Storage="_Num")]

        public int Num // Num 속성은 Num 컬럼과 매칭, 기본키 설정

        {

            get { return _Num; }

            set { _Num = value; }

        }

 

        private string _Name;

        [Column(Storage = "_Name")]

        public string Name

        {

            get { return _Name; }

            set { _Name = value; }

        }

 

        private string _Mobile;

        [Column(Storage = "_Mobile")]

        public string Mobile

        {

            get { return _Mobile; }

            set { _Mobile = value; }

        }

 

        private string _Email;

        [Column(Storage = "_Email")]

        public string Email

        {

            get { return _Email; }

            set { _Email = value; }

        }

    }

}


Form1.cs

using System.Data.Linq;  --> 추가

 

namespace WinLinqToSQL

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            // LINQ To SQL 방법으로 데이터 출력

            // Table 동일한 구조의 Entity 클래스가 만들어 졌다면...

           

            //[1] DataContext 인스턴스 생성

            DataContext context = new DataContext(

 "server=WINDOWS-XP\\SQLSERVER;database=AddressBook;uid=AddressBook;pwd=12345;");

           

            //[2] context GetTable<T> 팩터리 메서드로 테이블 매핑해서 가져오기

            Table<AddressBook> addr = context.GetTable<AddressBook>();

           

            //[3] LINQ Query 날리기

            var q = from a in addr select a;

           

            //[4] 출력

            foreach (var item in q)

            {

                listBox1.Items.Add(item.Name + ", " + item.Mobile);

            }

        }

    }

}


결과확인

[그림29-3]


WinLinqToSQL.zip


반응형