1. Trang chủ
  2. » Công Nghệ Thông Tin

LINQ TO SQL TUTORIAL

102 559 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 102
Dung lượng 3,43 MB

Nội dung

LINQ to SQL Tutorial From ScottGu blog o Hi Nam 2009 Thuvientailieu.net.vn LINQ to SQL Tutorial Mc lc Bi 1: S dng LNQ to SQL .6 LINQ to SQL l gỡ? Mụ hỡnh húa CSDL dựng LINQ to SQL: Tỡm hiu lp DataContext Cỏc vớ d LINQ to SQL .8 a Ly cỏc Product t CSDL b Cp nht mt sn phm CSDL .9 c Chốn thờm mt phõn loi mi v hai sn phm vo CSDL Xúa cỏc sn p h õ m 10 e Gi mt th t c 11 f Ly cỏc sn phm v phõn trang 12 Tng kt 12 Bi 2: nh ngha cỏc lp mụ hỡnh d liu .13 To mt mụ hỡnh d liuLINQ to SQL 14 Cỏc lp thc th 15 To cỏc lp thc th t C S D L .15 Cỏch t tờn v ng phỏp s nhiu 17 Quan h gia cỏc thc thờ 18 Delay/Lazy Loading 19 Dựng cỏc Stored Procedure 19 Dựng SPROCS cp nhxúa,thờm d liu .21 Tng kt 22 Bi 3: Truy C s d liu .23 Mụ hỡnh húa CSDL Northwind dựng LINQ to SQL 23 Ly cỏc sn phm 23 Trc quan húa cỏc cõu truy LINQ to SQL trỡnh g li 25 Gn ni cỏc cõu truy LINQ to SQL vo cỏc control LINQ to SQL 26 Data Sharping 27 Phõn trang kt qu truy 32 Tng kt 34 Bi 4: Cp nht c s d liu 35 CSDL Northwind c mụ hỡnh húa dựng LINQ to SQL 35 Change Tracking v DataContext.SubmitChangesO 36 Cỏc vớ d Insert v Delete 37 Thuvientailieu.net.vn LINQ to SQL Tutorial a Thờm mt sn phm 38 b Xúa cỏc sn phm 38 Cp nht thụng qua cỏc quan h .38 Transactions 40 Kim tra d liu v Business Logic 41 H tr kim tra cỏc giỏ tr thuc tớnh da trờn schemaca CSDL 41 H tr tựy bin vic kim tra giỏ tr cỏc thuc tớnh 41 H tr tựy bin vic kim tra tớnh hp l ca thc th 42 Tựy bin cỏc phng thc kim tra vic thờm/xúa/sa d liu 43 10 Nõng cao: Xem danh sỏch thay i cho Transaction 44 11 X lý cỏc thay i ng thi vi Optimistic Concurrency: 45 12 Dựng SPROCs hoc tựy bin logic cỏc cõu SQL: 45 Bi 5: S dng asp:LinqDataSource 47 ng dng mu m chỳng ta s xõy dng: 47 l gỡ v nú giỳp gỡ cho chỳng ta ? 48 Bc 1: nh ngha mụ hỡnh d liu 49 Bc 2: To danh sỏch sn phm .50 Bc 3: B cỏc ct khụng cn thit 54 Bc 4: Lc danh sỏch sn p h m .57 Bc 5: Thờm cỏc quy tc kim tra logic 60 Tng kt 63 Bi 6: Ly d liu dựng Stored Procedure 65 Dựng SPROC hay khụng SPROC? ú l mt 65 Cỏc bc ỏnh x v gi SPROC dựng LINQ to SQL 66 Cỏch ỏnh x mt SPROC vo mt DataContext ca LINQ 67 Cỏch gi SPROC mi c to .68 nh x kiu tr v ca phng thc SPROC vo mt lp mụ hỡnh d liu 69 X lý cỏc tham s thự tc dng OUTPUT 72 X lý cỏc th tc tr v nhiu kiu kt qu khỏc 73 H tr cỏc hm ngi dựng t nh ngha (UDF) 75 Tng kt 77 Bi 7: Cp nht d liu dựng Stored Procedure 78 Bc 1: To lúp truy xut d liu (cha dựng n cỏc thự tc) 78 Thờm cỏc quy tc kim tra d liu vo cỏc lp mụ hỡnh d liu .78 Thờm phng thc GetCustomerO vo lp DataContext 80 Thuvientailieu.net.vn LINQ to SQL Tutorial 10 Bc 2: Dựng lp truy cp d liu (cha s dng SPROC) 81 11 Ch mt giõy - Tụi ngh bi vit ny nh núi v vic dựng SPROC c m ??? 82 12 Cỏch s dng SPROC thc hin Insert/Update/Delete 83 13 Bc 3: Thờm mt Order bng cỏch dựng SPROC 83 14 Bc 4: Thc hin cp nht dựng SPROC 87 15 Bc 5: Dựng lp DAL ln na 89 16 Mt s u im ca vic dựng SPROC .89 Dựng cỏc tham s dng output: 89 S th no nu mt SPROC phỏt mt li? .90 Tụi cú th vit code thay vỡ dung ORM designer gi SPROC? 90 17 Tng kt 90 Bi 8: Thc thi cỏc biu thc SQL tựy bin 91 Dựng cỏc cõu truy SQL tựy bin vi LINQ to SQL 93 Dựng ExecuteQuery 93 Tựy bin cỏc biu thc SQL v theo vet (tracking) cỏc thao tỏc cp nht: 94 Tựy bin cỏc biu thc SQL vi cỏc lp ca bn 95 Tựy bin cỏc cõu SQL cho Inserts/Updates/Deletes 95 Tng kt 96 Di 9: Dựng biu thc LINQ tựy bin vi 97 Túm tt: dựng vi mt mnh where c khai bỏo 97 Dựng cỏc s kin Selecting vi 98 Thc hin cỏc phộp chiu truy vi s kin Selecting 101 Tng kt 103 Thuvientailieu.net.vn LINQ to SQL Tutorial Bi 1: S dng LINQ to SQL õy l bi vit u tiờn lot bi cú ch LINQ to SQL, cỏc bi ny s cho bn mt cỏi nhỡn khỏi quỏt, giỳp bn lm quen vúi LINQ, mt nhng cụng ngh mi cú NET 3.5 Lot bi ny c da trờn lot Tutorial ca ScottGu (http://weblogsasp.nescottgu) LINO to SQL l gỡ? LINQ to SQL l mt phiờn bn hin thc húa ca O/RM (object relational mapping) cú bờn NET Framework bn Orcas (nay l NET 3.5), nú cho phộp bn mụ hỡnh húa mt c s d liu dựng cỏc lúp NET Sau ú bn cú th truy c s d liu (CSDL) dựng LINQ, cng nh cp nht/thờm/xúa d liu t ú LINQ to SQL h tr y transaction, view v cỏc stored procedure (SP) Nú cng cung cp mt cỏch d dng thờm kh nng kim tra tớnh hp l ca d liu v cỏc quy tc vo mụ hỡnh d liu ca bn Mụ hỡnh húa CSDL dựng LINQ to SQL: Visual Studio Orcas ó tớch hp thờm mt ỡnh thit k LINQ to SQL nh mt cụng c d dng cho vic mụ hỡnh húa mt cỏch trc quan cỏc CSDL dựng LINQ to SQL Bi vit sau s i sõu hn vo cỏch dựng trỡnh thit k ny (bn cng cú th xem oan video ny xem cỏch tụi to mt mụ hỡnh LINQ to SQL) Bng cỏch dựng trỡnh thit k LINQ to SQL, tụi cú th d dng to mt mụ hỡnh cho CSDL mu Northwind ging nh di õy: Thuvientailieu.net.vn LINQ to SQL Tutorial Stylesheetl.css D efault.ispx.ci* N orthw ind d b m r Default.ispx I Method Pane V GetProũudsByCategoớy (lnt32 cateỗoằylD) Product Category s Properties t :5* !ỏ* ~ 2j* 23* ớ? - Propertiei ' ProducdD ProductName SupplierớO CdtegorylD QuntityPerUnt UnitPrice UnitslnStock UnitsOnCrder Reordertevel [>scont>ruied OrderDetoil Propôrtie5 ỡ OrderlD ỏ * ProducO ĩ? UnitPrice Quantity ij? Discount Categoryâ C jttgoiyN am c '.*? Descnpxion Picture Order ~ r*f Ift Properties OrdedD ^5* CustomerD EmployeelD OrderOate j j Required Date ShippedDate i f ShipVia Freight i j i ShipName ShipAddress ^ ShipOty ShipRegion 2^* ShipPostalCode ShipCountry Mụ hỡnh LINQ to SQL trờn nh ngha bn lp thc th: Product, Category, Order v OrderDetail Cỏc thuc tớnh ca mi lp ỏnh x vo cỏc ct ca bng tng ng CSDL Mi instance ca mt lp biu din mt dũng bng d liu Cỏc mi tờn gia bn lp thc th trờn biu din quan h gia cỏc thc th khỏc nhau, chỳng c to da trờn cỏc mi quan h primary-key/foreign-key CSDL Hng ca mi tờn ch mi quan h l mt - mt hay mt - nhiu Cỏc thuc tớnh tng ng s c thờm vo cỏc lúp thc th cỏc trng hp ny Ly vớ d, lp Category trờn cú mt mi quan h mt nhiu vi lp Product, iu ny cú ngha nú s cú mt thuc tớnh Categories l mt hp cỏc i tng Product Category ny Lp Product cng s cú mt thuc tớnh Category ch n i tng Category cha Product ny bờn Bng cỏc phng thc bờn tay phỏi bờn trỡnh thit k LINQ to SQL trờn cha mt danh sỏch cỏc SP tng tỏc vi mụ hỡnh d liu ca chỳng ta Trong vớ d trờn tụi ó thờm mt th tc cú tờn GetProductsByCategory Nú nhn vo mt categorylD v tr v mt chui cỏc Product Chỳng ta số xem bng cỏch no cú th gi c th tc ny mt on code bờn di Tỡm hiu lp DataContext Khi bn bm nỳt Save bờn mn hỡnh thit k LINQ to SQL, Visual Studio s lu cỏc lp NET biu din cỏc thc th v quan h bờn CSDL m chỳng ta va mụ hỡnh húa C mi mt file LINQ to SQL chỳng ta thờm vo solution, mt lp DataContext s c to ra, nú s c dựng cn truy hay cp nht li cỏc thay i Lp DataContext c to s cú cỏc thuc tớnh biu din mi bng c mụ hỡnh húa t CSDL, cng nh cỏc phng thc cho mi SP m chỳng ta ó thờm vo Thuvientailieu.net.vn LINQ to SQL Tutorial Ly vớ d, di õy l lp NorthwindDataContext c sinh da trờn mụ hỡnh chỳng ta to trờn: ~ X Class View L a * *3 - + _ j Project References r WebApplicationl B Category E i j Default ftlMyProduct -^ NorthwindOataContext j _ j B ase T y p # s đ DataContext ffl ^ Order - J OrderDetail â Product GetProductsByCategory(int?) V NorthwindDataContext(stimg) V NorthwindDataContext(System.Data.IDbConnection V - V NorthwindDataContextO T* Categories ^3* OrderDetails Orders Products i 111 '"3; - M-Irn r-.p orer *5Server; pferer j Class View Cỏc vớ d LINQ to SQL Mt ó mụ hỡnh húa CSDL dựng trỡnh thit k LINQ to SQL, chỳng ta cú th d dng vit cỏc on lnh lm vic vi nú Di õy l mt vi vớ d v cỏc thao tỏc chung x lý d liu: a Ly cỏc Product t CSDL on lnh di õy dựng cỳ phỏp LINQ ly v mt Enum erable cỏc i tng Product Cỏc sỏn phm c ly phi thuc phõn loi Beverages: ^NorthwindDatacontext db = new N orthwindD atacontext(); v a r p ro d u c ts = fro m p i n d b P r o d u c ts w h ere p c a te g o r y c a te g o r y N a m e = s e l e c t p; " B e v e g e s " VB: Thuvientailieu.net.vn LINQ to SQL Tutorial Dim db As New N o rth w in d D a ta c o n te x t Dim p ro d u c ts = From p i n d b P ro d u c ts _ w h ere p c a te g o r y c a te g o r y N a m e = " B e v e r a g e s " _ s e le c t p b Cõp nhõt mt sỏn phm CSDL on lnh di õy cho thy cỏch ly mt sn phm, cp nht li giỏ tin v lu li CSDL c#: N o rth w in d D a ta c o n te x t db = new N o r th w in d D a ta c o n te x tO ; P ro d u c t p ro d u c t = d b P r o d u c t s s i n g l e ( p => p p ro d u ctN am e = "T o y " ) ; p r o d u c t U n i t P r i c e = 99; p r o d u c t U n i t s l n s t o c k = 5; db.Subm i t c h a n g e s ( ) ; VB: Dim db a s New N o rth w in d D a ta c o n te x t Dim p ro d u c t = (Fro m p i n d b P ro d u c ts _ w h ere p P ro d u ctN am e = "T o y " _ s e le c t p ) s in g le p r o d u c t U n i t P r i c e = 99 p r o d u c t u n it s ln s t o c k = d b s u b m itc h a n g e s ( ) c Chốn thờm mụt phõn loai múi v hai sn phm vo CSDL on mó di õy biu din cỏch to mt phõn loi mi, v to hai sn phm mi v a chỳng vo phõn loi ó to Cỏ ba sau ú s c a vo c s d liu Chỳ rng tụi khụng cn phỏi t quỏn lý cỏc mi quan h primary key/foreign key, thay vo ú, tụi ch n gin thờm cỏc i tng Product vo hp Products ca i tng category, v ri thờm i tng category vo hp Categories ca DataContext, LINQ to SQL s bit cỏch thit lp cỏc giỏ tr primary key/foreign key mt cỏch thớch hp (Add ó c thay i bng InsertOnSubmit phiờn bn hin ti) Thuvientailieu.net.vn LINQ to SQL Tutorial NorthwindDatacontext db = neiv Nor th v.in d D ataco n textO ; / / C rea te new c ate g o ry and Products categ o ry categ o ry = new c a te g o ry Q ; category.categoryNam e = " S c o t t'S To ys"; product p ro d u ctl = new P ro d u c tO ; productl.ProductNam e = "Toy " ; Product product2 = new P ro d u c tO ; product2.ProductName = "Toy ; / / A sso c ia te Products w ith C ategory c a te g o ry p ro d u c ts A d d (p ro d u c tl); cate g o ry.P ro d u cts.A d d (p ro d u ct2 ); / / Add categ o ry to database and save changes d b ca te g o ri e s A d d (cate g o ry); db bubm ltchangesQ; VB: f Dim db as New NorthwindDatacontext ' C re a te New C ateg ory and Products Dim categ o ry As New c ate g o ry category.categoryN am e = " s c o t t 's Toys" Dim p ro d u c tl a s New Product productl.ProductNam e = "Toy 1" Dim product2 as New Product product2.ProductName = "Toy 2" ' A s s o c ia te products w ith c ate g o ry c a te g o ry p ro d u c ts.A d d (p ro d u c tl) c a te g o ry P ro d u c ts Add(product2) ' Add categ o ry to database and save changes d b C a te g o rie s.A d d (c a te g o ry) db subm itchangesQ d Xoa cac san pham Doan ma sau se bieu dien cach xoa tat ca cac san pham Toy khoi CSDL: (RemoveAll da dugc thay doi bang DeleteAllOnSubmit phien ban hien tai) C#: N orthw indD atacontext db = new N o rth w in d D ataco n text( ) ; va r to y p ro d u cts = from p in d b P ro d u cts where p P ro d u ctN am e.co n tain s(" T o y " ) s e le c t p; d b P ro d u c ts RemoveAl1 (to y p ro d u c ts ); db su b m itch an g esQ ; 10 Thuvientailieu.net.vn LINQ to SQL Tutorial VB: f * Dim db a s New N o rth w in d D a ta c o n te x t Dim t o y P r o d u c t s = From p i n d b P r o d u c ts _ w h ere p c a t e g o r y c a t e g o r y N a m e c o n t a in s ( " T o y " ) _ s e le c t p d b P ro d u c t s R e m o v e A l1 ( t o y P r o d u c t s ) db s u b m itc h a n g e s O e Goi mot thu tuc Doan ma duai day bieu dien cach lay cac thvrc the Product ma khong dung cu phap cua LINQ, ma goi den thu tuc GetProductsByCategory chung ta da them vao truac day N rang mot da lay ve ket qua, toi co the cap nhat/xoa va sau goi db.SubmitChanges() de cap nhat cac thay doi tra lai CSDL Northv.indDatacontext db = new Northv^incDatacontext(); var products - db.GetProductsByCategory(5); foreach (Product product in products) { product } Category CategorylD Discontinued V Equals v GetHashCode V GetType OrderOetails ProductID P ro d u ctN am e [string Product.ProductName VB: Dim db New N orthw indD atacontext as Dim pro d u cts = d b G e tP ro d u ctsB y c a te g o ry (S ) For Each product i n pro d u cts p ro d u ct Next |_ j CategorylD L T Discontinued V GetType | ProductID fcfel ProductName p f QuantityPerllnit L T ReorderLevel 111J T SupplierlD II Lj4 UnrtPrice UnitsInStock | Common | Public Property ProductNameQ As String| All 11 Thuvientailieu.net.vn LINQ to SQL Tutorial cho tham s @CustomerID @original_customerID ca SPROC, v Customer.CustomerlD "gc" vo cho Khi nhn "Ok" trờn a s ny, bn ó hon thnh vic ỏnh x cỏc tham s vo cỏc thuc tớnh T gi tr i, mi cp nht li giỏ tr cho i tng Customer v gi SubmitChanges(), th tc UpdateCustomer s c gi thay cho cõu lnh SQL ng Quan trng: Dự rng hin ti bn ó dựng SPROC cp nht, phng thc "OnPhoneChangingO" m chỳng ta ó to trc ú (trong bc ca bi ny) xỏc thc s in thoi c thc thi trc bt k thay i no c lu li hay "UpdateCustomer" c gi Chỳng ta cú mt cỏch rừ rng, sỏng sa hin thc húa cỏ quy tc x lý cng nh xỏc thc d liu, v cú th dựng chỳng m khụng ph thuc v vic chỳng ta ang dựng cõu lnh SQL ng hay SPROC 15 Bc 5: Dựng lúp DAL ln na Mt ó cp nht lp truy cp d liu (DAL) dựng SPROC thay vỡ cõu lnh SQL ng, bn cú th chy li cỏc cõu lnh tng t cỏc cõu lnh ta ó lm bc lm vic vi cỏc lp mụ hỡnh d liu: Dim n o rth w in d AS New N o rth w in d D ataco n te xt ' R e t r ie v e custom er Dim mycustomer AS Custom er = n o rth iv in d G e tc u s to m e r("A L F K l") ' update th e Contact Name and Phone Number JiyCustom er.contactN am e = " S c o tt G u th r ie " roytu stom er.Phone = 425-555-1212 ' c r e a t e New o rd e r f o r th e Custom er Dim order AS New order o rd e r.o rd e ro a te = Now() ord er RequiredDate = NowO AddDays(3) o r d e r S h ip c it y = "Redmond o rd e r.S h ip p o sta lco d e - "98052" ' A s s o c ia t e o rd e r w ith Customer tn y cu sto m e r.o rd e rs A d d (o rd e r) ' save a l l updates to th e database northwind subm itchangesO 'S* _ r Gi õy vic cp nht i tng Customer, v vic thờm cỏc i tng Order s c thc thi thụng qua th tc ó to thay vỡ dựng cỏc cõu SQL ng Cỏc quy tc kim tra cng c thc thi ht nh trc õy, v cỏc cõu lnh chỳng ta ó dựng s dng cỏc lp mụ hỡnh d liu cng hon ton tng t 16 Mụt s u im ca vic dựng SPROC Sau õy l mt vi ý nh cú th cú ớch cho bn vic dựng SPROC: Dựng cỏc tham s dng output: Trong phn trờn, tụi ó biu din cỏch chỳng ta cú th trỏ v giỏ tr OrderlD mi c to (õy l mt ct t tng CSDL) bng cỏch dựng mt tham s dng output Bn s khụng b gii hn vic trỏ v ch cỏc ct t tng - m tht s bn cú th trarveef cỏc giỏ tr cho bt k tham s no 89 Thuvientailieu.net.vn LINQ to SQL Tutorial ca SPROC Bn cú th dựng cỏch tip cn ny cho c trng hp Insert v update LINQ to SQL cú th ly giỏ tr tr v v dựng nú cp nht giỏ tr ca cỏc thuc tớnh ca cỏc i tng mụ hỡnh d liu m khụng cn thc thi thờm mt cõu truy th ly cỏc giỏ tr ó c to S th no nu mt SPROC phỏt mt li? Nu mt SPROC phỏt mt li thc hin vic Insert/Update/Delete, LIN to SQL s t ng hy v rollback ton b cỏc thay i ó to transaction kt hp vi li gi SubmitChanges() iu ny m bo rng d liu ca bn s luụn trng thỏi ỳng n Tụi cú th vit code thay vỡ dung ORM designer gi SPROC? Nh ó núi phn u bi vit ny, bn cú th dựng LINQ to SQL designer ỏnh x cỏc thao tỏc thờm/sa/xúa vo cỏc SPROC, hoc bn cng cú th thờm cỏc phng thc partial vo lp DataContext v vit lnh gi chỳng õy l mt vớ d v cỏch vit cỏc phng thc lúp partial ca NorthwindDataContext dựng UpdateCustomer gi mt th tc: ^ p a r t i a l void Updatecust0m er(cust0ner customer) customer o r ig in a l = c ( c u s t o m e r ) (C u s t o m e r s G e t o r ig in a lE n t it y s t a t e ( c u s t o m e r ))); t h i s.u p d a te c u sto m e rs(c u sto m e r Cu stom erID , cu sto m er companyName, cu sto m er contactN am e, cu sto m er c o n t a c t T i t l G, [F u n ctio n (N am e = "d b o u p d ate cu sto m e rs")] p u b lic i n t u p d ate cu sto m e rsc[P ara m e te r (Name=cu sto n ie riD " , D b Typ e= "N C h ar(5)")] s t r i n g cu sto m erlD , [Parameter(Name= lE x e c u te R e s u lt r e s u lt ô t h i s E x e c u t e M e th o d c a ll(th is , ((N e th o d ln fo )(M e th o d in fo G e tC u rre n tM e th o d O )), custom er r e t u r n ( ( i n t ) ( r e s u l t R e t u r r iv a lu e ) ) ; on lnh trờn thc chớnh l cỏi irc to bt! dựng T.TNQ to SQL designer ỏnh x SPROC v kt hp nú vi thao tỏc cp nht i tng Customer Bn cú th xem nú nh im u v sau ú tip tc thờm bt k lnh x lý no bn mun (vớ d: dựng giỏ tr tr v ca SPROC phỏt cỏc exception tng ng vi mó li nhn c, optimistic concurrency ) 17 Tng kt LINQ to SQL l mt trỡnh ỏnh x i tng (ORM) cc k mm Nú cho phộp bn vit cỏc on code theo kiu hng i tng mt cỏch rừ rng, sang sa ly, cp nht hay thờm d liu Hn ht, nú cho phộp bn thit k cỏc lp mụ hỡnh d liu m cỏch d dng, khụng ph thuc vo cỏch nú c lu hay np li t CSDL Bn cú thờt dựng trỡnh ORM xõy dng sn ly v hay cp nht d liu mt cỏch hiu qu bng cỏch dựng cỏc cõu SQL ng Hoc bn cng cú th cu hỡnh lp d liu dựng SPROC iu hay l cỏc on lnh ca bn dựng lp d liu ny, cng nh cỏc th tc kim tra logic u khụng ph thuc vo cỏch lu/np d liu thc s c dựng Trong bi tip theo ca lot bi ny, tụi s núi v mt s khỏi nim cũn li LINQ to SQL, bao gm: Single Table Inheritance, Deferred/Eager Loading, Optimistic Concurrency, v x lý cỏc ng cnh Multi-Tier 90 Thuvientailieu.net.vn LINQ to SQL Tutorial Bai 8: Thyc thi cac bieu thurc SQL bien Co mot vai ban da hoi toi viet cac bai la Lieu toi co the Idem soat hoan toan cac cau SQL duoc dung bai LINQ to SQL ma khong can phai viet cac SPROC? Trong bai viet toi se noi ve dieu - va thao luan cach ban co the viet cac cau SQL bien de truy van, cung nhu de them, sira hay xoa du lieu Trong bai viet nay, chung ta se dung mo hinh mo hinh du lieu duoc tao voi CSDL Northwind (xin hay doc phan de hoc cach dung VS 2008 de tao mo hinh nay): NorthwincLdbml Default.aspi * X Category S Properties f ProductID ProductName i f SupplieriD Categoryđ QuantityPerUnit UnitPrice i f UnitslnStock i f UnitsOnOrder Reordcrlevel i f Discontinued S Properties C 13 3 CategorylD CategoiyName Description Picture s O rder Detail Properties 13 OrderiD V3 Productâ i f UnitPrice Quantity Discount Create methods by dragging items from k rv r E.icltrtt onto this design surface Properties # i f OrderiD i f CustomerlD '3 EmployeetD CrderDate RequiredDate ShippedDate if if if if ShipVia freight ShipName ShipAddress ShipCity i f ShipRegion i f ShipPostalCode i f ShipCountry r Customer [S' i Properties W CustomerlD CompanyName i f ContactName ContactTitle Address ^ City Region PostalCode S f Country 2P Phone 'S to Trong phan 3, toi da cho cac ban thay cach dung ngon ngu LINQ mod duoc dua vao VB va C# de truy van mo hinh dÊr lieu d tren va tra ve mot tap doi tuong bieu dien cac dong/cot CSDL Vi du, ban co the them mot phuong thuc tro giup GetProductsByCategory vao lop DataContext mo hinh du lieu cua chung ta ma no se dung each truy van LINQ de tra ve cac doi tuong Product tir CSDL: 91 Thuvientailieu.net.vn LINQ to SQL Tutorial VB: N o rth w in d D ataco n tex t.v b Default.aspx |Ê J (G eneral) ^ P a rtia l P u b lic c l a s s P u b lic (Declarations) N o rth w in d D a ta c o n te x t F u n c tio n G e tP r o d u c ts B y C a te g o ry (B y v a l c a te g o ry ld as In te g e r) As lE n u ro e b le ( O f P r o d u c t) R e t u r n F ro m p I n M e P r o d u c t s _ w h e re p c a te g o r y iD = c a t e g o r y ld _ s e le c t p End F u n c tio n End C l a s s C#: N orthwindDataContext.es* Default.aspx.es Northwind.dbml Default.aspx ^LINQToSQL8.NorthwindDataContext f u s i n g s y s te m ; I u s in g s y s t e m L in q ; u s in g s y s t e m c o l l e c t i o n s G e n e r i c ; (3 nam espace l in q t o s q l II i p u b lic p a r t i a l { c l a s s N o rth w in d D a ta c o n te x t p u b lic lE r u r r e r a b le< P roduct> G e t P r o d u c t s B y C a t e g o r y ( in t c a t e g o r y lD ) { r e t u r n fro m p in t h i s P ro d u c ts w h ere p c a t e g o r y iD == c a t e g o r y lD s e l e c t p; } } } Mot ban da dinh nghia phuang thuc LINQ nhu tren, ban co the viet lenh giong nhir dirai day de dung no lay ve cac san pham, va duyet qua tap ket qua tra ve: VB: Dim n o r t h w i n d D im p r o d u c t s For as - New N o r t h w i n d D a t a c o n t e x t n o rth w in d G e tP ro d u c ts B y C a te g o ry (l) E ach p ro d u c t p ro d u c t In p ro d u c ts N ext i f Category a t _ i f D iscontinued i f P roductđ i f ProductN am e i f QuantityPerUnit if if If if ReorderLevel SupplierlD UnitPrice UnitsInStock C om m on All 92 Thuvientailieu.net.vn LINQ to SQL Tutorial Khi biu thc LINQ bờn phng thc GetProductsByCategorý c thc thi, trỡnh qun ly LNQ to SQL s t ng thc thi cõu SQL ng ly v d liu Product v to danh sỏch cỏc i tng Product Bn cú th dựng trỡnh debug xem cỏch biu thc LINQ ny thc thi Dựng cỏc cõu truy SQL tựy bin vúi LNQ to SQL Trong vớ d mu trờn chỳng ta ó khụng vit bt k cõu lnh SQL no truy d liu v ly v cỏc ng tng cú kiu Product Thay vỡ vy, LINQ to SQL s t ng dch biu thc LINQ thnh cõu lnh SQL chỳng ta v thc thi nú CSDL Nhng liu nu chỳng ta mun kim soỏt hon ton cõu lnh SQL c thc thi vi CSDL, v khụng muụn LIN to SQL lm iu ú t ng? Mt cỏch lm iu ny l dựng mt SPROC ging nh tụi ó trỡnh by bi v bi Mt cỏch khỏc l dựng phng thc ExcecuteQuery lp DataContext thc thi mt cõu SQL chỳng ta cung cp Dựng Executeuery Phng thc ExecuteQuery nhn vo mt cõu SQL, cựng vi mt cỏc tham s m ta cú th dựng to nờn cõu SQL Bng cỏch dựng nú, bn cú th thc thi bt k cõu lnh SQL bn mun vi CSDL (k cỏc cõu lnh JOIN nhiu bng) iu lm cho ExecuteQuery thc s hu dng l nú cho phộp bn ch cỏch nú tr v d liu Bn cú th lm c iu ny bng cỏch truyn mt i tng cú kiu mong mun nh mt tham s ca phng thc, hay dựng kiu generic Vớ d, bn cú th thay i phng Ihc GetProduclsByCalegoryO e to trc õy phiờn bn dựng mt biu thc LINQ - dựng phng thc ExecuteQuery thc thi mt cõu SQL vi CSDL v tr v mt i tng Product nh kt qu: - " " ' P u b l i c F u n c t io n G e t P r o d u c t s B y c a t e g o r y (B y v a l c a t e g o r y ld AS i n t e g e r ) AS lE n u m e r a b le ( o f R e t u rn E x e c u te Q u e ry C o f P r o d u c t ) ( " s e l e c t * fro m p ro d u c ts w h ere c a t e g o r y ! d = { } " , c< ^ E n d F u n c t io n ^ p u b lic p a r t ia l { c l a s s N o rth v 'in d D a ta c o n te x t p u b lic :E n u m e b le < P ro d u c t> G e t P r o d u c t s B y c a t e g o r y C in t c a t e g o r y lD ) t r e t u r n E x e c u te Q u e ry < P ro d u c t> (@ "s e le c t * fro m p ro d u c ts w h ere c a t e g o r y ! d = { } , } V i Chỳng ta Cể the gi GetProductsByCategoryO dựng cựng cỏch nh trc ỏy: 93 Thuvientailieu.net.vn LINQ to SQL Tutorial s Dim n o rth w in d As New N o rth w in d D a ta C o n te x t Dim p ro d u c ts = n o r t h w in d G e t P r o d u c t s B y c a t e g o r y ( l) F o r E a c h p ro d u c t i n p ro d u c ts p ro d u c t N ext |5 * Category * life li CateqorylD j^ f1 Discontinued |jõ* ProductID J5* ProductName = J-? QuantityPerUnit ReorderLevel i SupplierlD UnitPrice UnitsInStock Common All Nhng khụng nh trc õy, trng hp ny cõu SQL tựy bin s c gi thay cho cõu SQL ng c to bi biu thc LINQ Tựy bin cỏc biu thc SQL v theo vt (tracking) cỏc thao tỏc cp nht: Mc nhiờn, bn ly v mt mụ hỡnh d liu dựng LINQ to SQL, nú s lu li cỏc thay i m bn lm Ncu gi phng thc SubmitChangcsO trcn lúp DataContcxt, nú SC lu li cỏc thay i vo CSDL Tụi ó núi chi tit v ny phn ca lot bi ny Mt ong nhng tớnh nng ni tri ca ExecuteQuery l nú cú th kt hp hon ton vo quỏ trỡnh theo vt v cp nht li mụ hỡnh d liu Vớ d, bn cú th vit on lnh di õy ly v tt c cỏc sn phm t mt chng loi no ú v gim giỏ ton b 10%: Dim n o rth w in d a s New N o rth w in d D a ta c o n te x t Dim p ro d u c ts = n o r t h w in d G e t P r o d u c t s B y C a t e g o r y (l) F o r E a ch p ro d u c t i n p ro d u c ts p r o d u c t U n i t P r i c e = p r o d u c t U n i t P r i c e * N ext n o r th w in d s u b m it c h a n g e s Bi vỡ chỳng ta ó ch rừ kiu tr v ca cõu lnh ExecuteQuery phcrng thc GetProductsByCategory, vy LINQ to SQL s bit cỏch d dũ cỏc thay i trờn cỏc di tng Product m chỳng ta tr v, v gi SubmitChangesO trờn di tng ú, chỳng s c lu li SCDL 94 Thuvientailieu.net.vn LINQ to SQL Tutorial Tựy bin cỏc biu thc SQL vúi cỏc lúp ca bn Phng thc ExecuteQueryO cho phộp bn bt k lp no nh kiu tr v ca cõu truy Lp ny khụng nht thit phi c to bi trỡnh LINQ to SQL designer, hay phi tha k t bt k class/interface no Vớ d, bn cú th nh ngha mt lp ProductSummary mi cha cỏc thuc tớnh l ca Product nh di õy (chỳ ý l chỳng ta dựng c tớnh Automatic Properties mi cú c #): p u b lic c l a s s P ro d u ctsu m m ary { p u b lic i n t p u b lic s t r i n g p u b lic D e c i m a l ? P ro d u c t lD { g e t; s e t ; } ProductN am e { g e t ; s e t ; } u n it P r ic e { g e t; s e t ; } } Chỳng ta cú th sau ú to mt phng thc tờn l GetProductSummariesByCategoryO lp NorthwindDataContext, nú s tr v cỏc kt qu da trờn kiu ProductSummary ý l cõu SQL di õy ch yờu cu cỏc thuc tớnh ca Product nú cn - ExecuteQuery s t bit cỏch a cỏc giỏ tri ú vo cỏc i tng ProductSummary m nú s tr v p u b lic p a r t ia l c la s s N o rth v in d D a ta C o n te x t { p u b lic lEn u m erab le< P ro d u ctSu in m ary> GetProductSum m ariesBycategory(int categoryXD) > re tu rn ExecuteQuery(@"se1ect P ro du ctld, ProductName, u n itP ric e from products where c a te g o ryid = {0 }", categ o rylD ); } Sau ú chỳng ta cú th dựng phng thc ny truy v duyt qua kt qu t v: db = new N o r t h w in d D a t a C o n t e x tO ; db.G e t P r o d u c t s u m m a r ie s B y c a t e g o r y (l); N o rth w in d D a ta C o n te x t v a r p ro d u c t s - fo re a c h (p ro d u c tsu m m a ry p i n p r o d u c t s ) { p-l } vguas V GetHashCode V GetType ProductlD 3* P ro d u ctN am e V ToString '3 UnitPrice Tựy bin cỏc cõu SQL cho Inserts/Updates/Deletes Thốm vo vic dựng cỏc biu thc SQL tựy bin truy vn, bn cng cú th dựng chỳng thc hin cỏc thao tỏc nh thờm/xúa/sa Chỳng ta cú th lm c iu ny bng cỏch to cỏc phng thc partial lp DataContext tng ng cỏc thao tỏc Insert/Update/Delete cho thc th m chỳng ta mun thay i V chỳng ta 95 Thuvientailieu.net.vn LINQ to SQL Tutorial sau ú cú th dựng phng thc ExecuteCommand thc thi cỏc cõu SQL cn thit Vớ d, thay th hnh vi Delete mc nhiờn cho lp Product, bn cú th nh ngha mt phng thc partial DeleteProduct nh sau: p u b lic p a r t i a l c l a s s N orthw indD ataC o ntext { p a r t i a l v o id D e le te p ro d u c t(P ro d u c t in s t a n c e ) { Executecom m andC'DELETE FROIô1 P ro d u c ts where P ro d u c tid = {0 > " , in s t a n c e P r o d u c t lD ) ; > v i / V bõy gi, nu bn vit a code di õy xúa mt Product no ú CSDL, LINQ to SQL s gi phng thc DeleteProduct - v ú cỏc cõu SQL tựy bin s c thc thi thay th cho cõu SQL c sinh t ng bi LINQ to SQL: N s N orthv:indD atacontext db = new N orthw indD ataC ontextO ; / / R e trie v e a s p e c i f i c product Product product = db Pro d u cts.sin g le(p = > p p ro d uctN am e = "My P ro d u c t"); / / Mark i t to be d eleted d b P ro d u cts.R e m o ve (p ro d u ct); / / update database db s u b m it c h a n g e s Q ; Tng kt Trỡnh qun lý LINQ to SQL t ng to v thc thi cỏc cõu SQL ng thc hin cỏc cõu truy vn, cp nht, thờm v xúa d liu CSDL i vi mt s trng hp, bn mun kim soỏt hon ton cõu lnh SQL c thc thi, bn cú th dựng cỏc th tc SPROC, hay cng cú th vit cỏc cõu SQL ca riờng bn iu ny cung cp kh nng tựy bin mnh m 96 Thuvientailieu.net.vn LINQ to SQL Tutorial Bi 9: Dựng biu thc LINQ tựy bin vúi Trong phn ca lot bi ny tụi ó gii thiu control mi NET 3.5 v núi v cỏch dựng nú gn ni cỏc control ASP.NET d dng vo cỏc mụ hỡnh d liu LINQ to SQL Tụi cng ó trỡnh by mt chỳt vờ cỏch dựng chỳng mt bi vit sau ú núi v control Trong cõ hai bi vit trờn, cỏc cõu truy c thc hin u tng i d hiu (mnh Where lm vic ch vi mt bng d liu) Trong bi vit hụm tụi s biu din cỏch tn dng kh nng xõy dng cỏc cõu truy nhanh chúng vi LINQ dựng LinqDataSource, v cỏch bn cú th dựng bt k biu thc LINQ no thc hin truy vi nú Túm tt: dựng vúi mt mnh where c khai bỏo Trong bi vit ú tụi ó biu din cỏch bn cú th dựng cỏc b lc cú sn ca LinqDataSource khai bỏo nhanh mt b lc trờn mt mụ hỡnh d liờu LINQ to SQL Vớ d, cho l bn ó to mt mụ hỡnh d liu LINQ to SQL ca CSDL Northwind (cỏch dựng ó c núi n phn cua lot bi ny), chỳng ta cú cú th khai bỏo mt control trờn trang vi mt mnh m nú ch tr v cỏc sn phm thuc mt chng loi no ú (c ch qua tham s categoryid ca chui query string): < asp:LinqD atasource ID -"ProductoataSource" ru n a t-" se rv e r" ContextTypeName-"Northw1ndDataContext" TableN am e= "Products w h ere= "categ o rylD == @ catộgoryi "> < asp :qu erystring param eter D e fa u ltv a lu e -" !'' Name-"categoryiD" QueryStr1ngFie1d="categoryid'' T yp e-"ln t3 2" /> < / a s p : L1nqD at a s o u r c e> Chỳng ta cú th tr mt control n datasource ó to v cho phộp phõn trang, chinh sa v sp xp: x I

Ngày đăng: 14/08/2016, 18:36

TỪ KHÓA LIÊN QUAN