Sie sind auf Seite 1von 22

Data Access using ADO.

NET
Lesson 1
Disconnected Data Access
Previous technologies connected oriented. Failed: o Open connection resource intensive Difficult to scale ? ADO.NET = disconnected b default ! connection "aintained onl #hile perfor" re$uisite action %e.g. perfor" $uer & 'elies on ( co"ponents ! Data)et and DataProvider ?

Data Set
? Disconnected* in "e"or data representation +oad data into Data)et fro" an valid source o ),+ )erver Access Database -.+ file ? /ontains 01 DataTable ob2ects %represent single table& o DataTable structure deter"ined b sche"a* co"prises of ? Data/olu"ns collection %enu"erates colu"ns of a table& /onstraint collection %enu"erates table constraints& ? 3 Data'elations collection o /reate associations bet#een different table ro#s b enu"erating Data'elation ob2ects ? E4tendedProperties o store custo"ised data ? )E+E/T state"ent to generate result set Date of generation Etc. o Persisted #ith sche"a infor"ation for ? Data)et DataTable Data/olu"n

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

Data Provider
? Provides and "aintains lin5 to database +ight#eight )et of related co"ponents o /onnection ? actual connection to D6 .NET provides t#o providers ! ),+ )erver and O+E D6 ? ),+ )erver "uch lighter than O+E D6 ? 7nfo re$uired for connection stored in /onnection)tring propert ? )i"ilar to previous O+E D6 version Onl set #hen connection closed .ust al#a s specif server %can be set to local& )ecurit info %e.g. pass#ord& not returned unless 8Persist )ecurit 7nfo = true9 present Argu"ent E4ception generated if /onnection)tring cannot be parsed Don:t need to specif provider %e.g. ),+O+ED6& if using )$l/onnection Avoid using ;D+ %;niversal Data +in5& files as parsed ever ti"e connection opened %because file "a have changed& ! use static connection string ? Auto"aticall pooled ? s ste" #ill reuse e4isting connection if /onnection)tring "atches and not currentl in use %i.e. /lose%& or Dispose%& has been called& connection re"oved if lifeti"e e4pired or connection severed ? 'aises ( events related to connection state ? 7nfo.essage ! <arnings and 7nfor"ation "essages fro" data source %errors raise e4ceptions& )tate/hange ! #hen state of connection changes* deter"ine state change b co"paring Original)tate and /urrent)tate properties
Use subject to our Ter"s and /onditions Written By 'oss Fruen

/o""and ? E4ecute D6 co""ands across /onnection .NET provides t#o providers ! ),+ )erver and O+E D6 /onstructor ta5es optional args ? ),+ state"ent to e4ecute at data source /onnection ob2ect Transaction ob2ect ? E4ecuteNon,uer ! e4ecute co""ands #ith no return values* e.g. Data Definition +anguage DD+ state"ents li5e =/'EATE TA6+E: and so"e )Ps E4ecute)calar ! e4ecute co""ands returning single value %value of first colu"n of first ro# in result set& E4ecute'eader ! retrieve result as strea" of data via Data'eader ob2ect <hen using #ith stored proc "a set /o""andT pe propert to )toredProcedure and use Para"eters propert to access input* output and return values %if using E4ecute'eader then output and return values not available until Data'eader closed& o Data'eader ? /annot be directl instantiated For#ard onl * read onl * connected recordset fro" database /an increase app perfor"ance due to reduced s ste" overhead %onl 3 ro# in "e"or at a ti"e& ;seful #hen do not need to 5eep data cache in "e"or Onl one ro# in "e"or at a ti"e ! lo# overhead 'e$uires e4clusive use of /onnection ob2ect during its lifeti"e o DataAdapter ? /ore of disconnected data access Facilitates co""unication bet#een database and Data)et Fills DataTable or Data)et #ith info fro" D6 #hen Fill "ethod called Trans"it changes bac5 to D6 #hen ;pdate called %using appropriate insert* delete or update co""and& > properties represent database co""ands ? )elect/o""and ! contains co""and te4t or ob2ect to select data fro" db. E4ecuted #hen Fill "ethod called. 7nsertco""and ! contains co""and te4t or ob2ect to insert data into table. Delete/o""and ! contains co""and te4t or ob2ect to delete ro# fro" table. ;pdate/o""and ! contains co""and te4t or ob2ect to update data in db.

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

DataReader Vs DataSet
;se Data)et for follo#ing o 'e"ote data bet#een tiers or fro" -.+ <eb )ervice D na"ic data interaction ? 6inding to For" /ontrols /o"bining and relating data fro" "ultiple sources o /ache data locall Provide hierarchical -.+ vie# of data ! use -)+T or -Path $uer on data Perfor" e4tensive processing #ithout re$uiring open connection to data source ? Data'eader o 7"proved perfor"ance ? )ave "e"or consu"ed b Data)et )ave ti"e used to fill create and fill Data)et ?

Lesson 2
Connecting to DB
? Easiest #a to i"ple"ent connection = use 7DE )erver E4plorer #indo# Available data connections = child nodes of Data /onnections node /reate ne# connection b right clic5ing Data /onnections and choosing Add /onnection ! configure details on Data +in5 Providers dialog bo4 Drag connection fro" )erver E4plorer to designer ! creates 1 configures /onnection ob2ect Fro" code create connection ob2ect and set connection string OleDbConnection myConnection = new OleDbConnection();

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

myConnection.ConnectionString = Provider=Microsoft.Jet.O !D".#.$;D%t%So&rce=C'(()ort*win d.mdb+;

Using Command
? Do not re$uire DataAdapter to interact #ith D6 /reate: o Drag stored procedure fro" )erver E4plorer to designer Drag )$l/o""and ? OleDb/o""and fro" data tab or toolbo4 Declare and instantiate instance of /o""and ob2ect ? /o""andT pe propert indicates its t pe o Te4t ! /o""andTe4t contains ),+ $uer )toredProcedure ! /o""andTe4t contains na"e of )P TableDirect ! na"e of table%s& indicated b /o""andTe4t. 'eturns all colu"ns and ro#s of specified tables ? )et /onnection propert to active connection Para"eters are values that fill placeholders in co""and te4t at run ti"e* stored in Para"eters propert and read at runti"e
S,lConnection nwindConn = new S,lConnection(-D%t% So&rce=loc%l*ost;.ntegr%ted Sec&rity=SSP.;.niti%l C%t%log=nort*wind-); S,lComm%nd s%lesCMD = new S,lComm%nd(-S%les"yC%tegory-/ nwindConn); s%lesCMD.Comm%nd0y1e = Comm%nd0y1e.StoredProced&re; S,lP%r%meter myP%rm = s%lesCMD.P%r%meters.2dd(-3C%tegory)%me-/ S,lDb0y1e.)4%rC*%r/ 56); myP%rm.4%l&e = -"ever%ges-; nwindConn.O1en(); S,lD%t%7e%der my7e%der = s%lesCMD.!8ec&te7e%der(); Console.9rite ine(-:$;/ :5;-/ my7e%der.<et)%me($)/ my7e%der.<et)%me(5)); w*ile (my7e%der.7e%d()) : Console.9rite ine(-:$;/ =:5;-/ my7e%der.<etString($)/ my7e%der.<etDecim%l(5)); ; my7e%der.Close(); nwindConn.Close();

)o"e properties e4posed b Para"eters collection o DbT pe ! t pe represented in /T) %co""on t pe s ste"& Direction @ is par" 7nput* Output or 7nputOutput OleDbT pe ! t pe as e4ists in database
Use subject to our Ter"s and /onditions Written By 'oss Fruen

Para"eterNa"e ! na"e to be used as 5e in code %if not using ordinal& Precision ! "a4i"u" nu"ber of digits in value %nu"eric and deci"al& )cale ! nu"ber of deci"al places in value %nu"eric and deci"al& )iAe ! "a4i"u" siAe of data in colu"n %string and binar & )ource/olu"n ! colu"n to loo5 up or "ap values )ourceBersion ! version of colu"n to use #hen editing Balue ! Balue represented b para"eter ? /an provide /o""and6ehavior argu"ent to e4tract 6+O6s fro" database. )et to /o""and6ehavior.)e$uentialAccess and use Cet6 tes%& to access data. .ust retrieve data in order presented ! once reader steps be ond that colu"n it is no longer available

S,lConnection 1&bsConn = new S,lConnection(-D%t% So&rce=loc%l*ost;.ntegr%ted Sec&rity=SSP.;.niti%l C%t%log=1&bs;-); S,lComm%nd logoCMD = new S,lComm%nd(-S! !C0 1&b>id/ logo ?7OM 1&b>info-/ 1&bsConn); ?ileStre%m fs; "in%ry9riter bw; ?ileStre%m obBect. int b&fferSiCe = 5$$; byteDE o&tbyte = new byteDb&fferSiCeE; long retv%l; long st%rt.nde8 = $; @@ 9rites t*e " O" to % file @@ (A.bm1). @@ Stre%ms t*e " O" to t*e

@@ @@ @@ @@ @@ @@ @@

SiCe of t*e " O" b&ffer. 0*e " O" byteDE b&ffer to be filled by <et"ytes. 0*e bytes ret&rned from <et"ytes. 0*e st%rting 1osition in t*e " O" o&t1&t.

string 1&b>id = --;

@@ 0*e 1&blis*er id to &se in @@ t*e file n%me.

@@ O1en t*e connection %nd re%d d%t% into t*e D%t%7e%der. 1&bsConn.O1en(); S,lD%t%7e%der my7e%der = logoCMD.!8ec&te7e%der(Comm%nd"e*%vior.Se,&enti%l2ccess); w*ile (my7e%der.7e%d()) : @@ <et t*e 1&blis*er id/ w*ic* m&st occ&r before getting t*e logo. 1&b>id = my7e%der.<etString($); @@ Cre%te % file to *old t*e o&t1&t. fs = new ?ileStre%m(-logo- F 1&b>id F -.bm1-/ ?ileMode.O1enOrCre%te/ ?ile2ccess.9rite); bw = new "in%ry9riter(fs); @@ 7eset t*e st%rting byte for t*e new " O". st%rt.nde8 = $;

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

@@ 7e%d t*e bytes into o&tbyteDE %nd ret%in t*e n&mber of bytes @@ ret&rned. retv%l = my7e%der.<et"ytes(5/ st%rt.nde8/ o&tbyte/ $/ b&fferSiCe); @@ Contin&e re%ding %nd writing w*ile t*ere %re bytes beyond t*e @@ siCe of t*e b&ffer. w*ile (retv%l == b&fferSiCe) : bw.9rite(o&tbyte); bw.?l&s*(); @@ 7e1osition t*e st%rt inde8 to t*e end of t*e l%st b&ffer %nd @@ fill t*e b&ffer. st%rt.nde8F= b&fferSiCe; retv%l = my7e%der.<et"ytes(5/ st%rt.nde8/ o&tbyte/ $/ b&fferSiCe); ; @@ 9rite t*e rem%ining b&ffer. bw.9rite(o&tbyte); bw.?l&s*(); @@ Close t*e o&t1&t file. bw.Close(); fs.Close(); ; @@ Close t*e re%der %nd t*e connection. my7e%der.Close(); 1&bsConn.Close();

Using DataReaders
? /reated i"plicitl System.D%t%.S,lClient.S,lD%t%7e%der myS,l7e%der; myS,l7e%der = myS,lComm%nd.!8ec&te7e%der(); ? : obBect myObBect = myD%t%7e%derDGE; obBect myOt*erObBect = myd%t%7e%derDC&st.D+E; ; ? ? Data e4posed b Data'eader t pes as ob2ects /an retrieve as t ped data ! Cet follo#ed b t pe na"e
Written By 'oss Fruen

Access colu"ns si"pl ! either b ordinal %based fro" 0& or colu"n na"e w*ile(myS,l7e%der.7e%d())

Use subject to our Ter"s and /onditions

o e.g. Cet6oolean%D& .ust 5no# ordinal %doesn:t #or5 #ith colu"n na"e& /an retrieve ordinal fro" colu"n na"e using CetOrdinal%& "ethod ;seful if 5no# t pe of particular colu"n /an retrieve "ultiple result sets fro" single co""and o )et /o""andT pe of /o""and ob2ect to Te4t )eparate ),+ state"ents using E Each ),+ state"ent e4ecuted se$uentiall * each result set returned separatel b Data'eader First result set returned auto"aticall fro" Data'eader )ubse$uent result sets accessed b calling Ne4t'esult%& "ethod do : w*ile(my7e%der.7e%d()) : @@ oo1 t*ro&g* records of 7ecordSet ; ; w*ile (my7e%der.)e8t7es&lt()); E4ecuting ad hoc ),+ $ueries o First build co""and string )et /o""andTe4t and /onnection properties for /o""and ob2ect at construction string Cmd = D! !0! A ?7OM !m1loyees 9H!7! )%me=I+ J %String J I+; OleDbComm%nd myComm%nd = new OleDbComm%nd(Cmd/ myConnection); myConnection.O1en(); myComm%nd.!8ec&te)onK&ery(); myConnection.Close(); ? Obtain sche"a info about result using Cet)che"aTable%& "ethod. 'eturns DataTable populated #ith sche"a for current result set. /ontains one ro# for each colu"n in result set* each colu"n "aps to a propert of colu" returned in result set #here /olu"nNa"e = na"e of propert and value is value of propert D%t%0%ble sc*em%0%ble = my7e%der.<etSc*em%0%ble(); fore%c* (D%t%7ow my7ow in sc*em%0%ble.7ows) : fore%c* (D%t%Col&mn myCol in sc*em%0%ble.Col&mns) : Console.9rite ine(myCol.Col&mn)%me F - = - F
Use subject to our Ter"s and /onditions Written By 'oss Fruen

my7owDmyColE); ; Console.9rite ine(); ; ? Al#a s call /lose%& "ethod #hen finished #ith Data'eader

Creating Data Adapters


+in5 data source and Data)et @ providing functionalit to retrieve data* populate Data)et and perfor" updates .anages e4change bet#een single DataTable in Data)et and data source. Data)et fre$uentl contains "ultiple DataTables ! create DataAdapter for each DataTable ( pri"ar adapters o )$lDataAdapter OleDbAdapter ? /reate DataAdpter o 6 )erver E4plorer ? Drag table fro" Data /onnection node of )erver E4plorer to Designer <indo# /an return subset of colu"ns in table b selection desired colu"ns fro" Data /onnection node to )erver E4plorer o 6 Data Adapter /onfiguration <iAard ? Drag DataAdapter fro" Data tab of toolbo4 into Designer <indo# )elect appropriate Data /onnection fro" #iAards drop do#n list /hoose ,uer T pe ? ),+ )tate"ents Ne# )tored Procedures E4isting )tored Procedures ? Cenerate $uer ? choose appropriate stored procedure o 6 /ode ?

Using Data Adapters


? Populate Dataset #ith data using DataAdapter fill "ethod D%t%Set myD%t%Set = new D%t%Set(); @@ 2ss&me e8istence of D%t% 2d%1ter n%med myD%t%2d%1ter myD%t%2d%1ter.?ill(myD%t%Set/ C&stomers+); ? ? A single Data)et can be target of "ultiple Fill co""ands ! each DataAdapter responsible for a single table held #ithin the Data)et Previe# Data returned b DataAdapter b selecting =Previe# Data: fro" Data "enu o Available DataAdapter ob2ects listed in drop@do#n "enu
Written By 'oss Fruen

Use subject to our Ter"s and /onditions

/lic5 Fill button to e4ecute DataAdapter Fill%& "ethod ? 7"plicitl opens and closes the associated connection. /an i"prove perfor"ance b "anuall opening and closing connection around series of operations.

@@ Po1&l%te list of c&stomers from SK L$$$ d%t%b%se %nd Orders from @@ 2ccess d%t%b%se/ est%blis* rel%tion between t%bles/ dis1l%y list @@ of c&stomers %nd t*eir orders S,lConnection c&stConn = new S,lConnection(-D%t% So&rce=loc%l*ost;.ntegr%ted Sec&rity=SSP.;.niti%l C%t%log=nort*wind;-); S,lD%t%2d%1ter c&stD2 = new S,lD%t%2d%1ter(-S! !C0 A ?7OM C&stomers-/ c&stConn); OleDbConnection orderConn = new OleDbConnection(-Provider=Microsoft.Jet.O !D".#.$;- F -D%t% So&rce=c'((Progr%m ?iles((Microsoft Office((Office((S%m1les((nort*wind.mdb;-); OleDbD%t%2d%1ter orderD2 = new OleDbD%t%2d%1ter(-S! !C0 A ?7OM Orders-/ orderConn); c&stConn.O1en(); orderConn.O1en(); D%t%Set c&stDS = new D%t%Set(); c&stD2.?ill(c&stDS/ -C&stomers-); orderD2.?ill(c&stDS/ -Orders-); c&stConn.Close(); orderConn.Close(); D%t%7el%tion c&stOrder7el = c&stDS.7el%tions.2dd(-C&stOrders-/ c&stDS.0%blesD-C&stomers-E.Col&mnsD-C&stomer.D-E/ c&stDS.0%blesD-Orders-E.Col&mnsD-C&stomer.D-E); fore%c* (D%t%7ow 17ow in c&stDS.0%blesD-C&stomers-E.7ows) : Console.9rite ine(17owD-C&stomer.D-E); fore%c* (D%t%7ow c7ow in 17ow.<etC*ild7ows(c&stOrder7el)) Console.9rite ine(-(t- F c7owD-Order.D-E); ;

Features 7nsert/o""and* ;pdate/o""and and Delete/o""and properties that are called #hen DataAdapter encounters change to Data'o# #2e" processing ;pdate%& "ethod. 7f call ;pdate%& before appropriate co""and set %e.g. no Delete/olu"n for deleted ro#s& then e4ception thro#n. Add Pri"ar Fe constraint details using Fill)che"a "ethod%& prior to calling Fill%& on Data Adapter. Note* if Auto7ncr"ent colu"n found the Data Adapter #ill have Auto7ncr"ent set to T';E* but ou #ill have to set
Written By 'oss Fruen

Use subject to our Ter"s and /onditions

Auto7ncre"ent)tep and Auto7ncr"entFe "anuall . Fil)che"a%& is costl to call ! if 5no# pri"ar @5e infor"ation at design ti"e then these should be set e4plicitl to increase perfor"ance.
@@ Obt%in sc*em% vi% ?illSc*em%() D%t%Set c&stDS = new D%t%Set(); c&stD2.?illSc*em%(c&stDS/ Sc*em%0y1e.So&rce/ -C&stomers-); c&stD2.?ill(c&stDS/ -C&stomers-); @@ Obt%in sc*em% vi% ?ill() D%t%Set c&stDS = new D%t%Set(); c&stD2.MissingSc*em%2ction = MissingSc*em%2ction.2dd9it*Mey; c&stD2.?ill(c&stDS/ -C&stomers-);

Table.appings per"it use of colu"n na"es in DataTable different to those in database* e.g. to create "apping called Authors.apping for the . Authors table use
worN2d%1ter.0%bleM%11ings.2dd(2&t*orsM%11ing+/ My2&t*ors+);

7f no "apping na"e is passed to Fill%& "ethod* then the DataAdapter #ill loo5 for "apping called 8Table9. 7f an colu"n is not present in "apping then it is provided #ith default na"e of )ource/olu"nN %N being incre"ented&. +i5e#ise if no table na"e provided then default na"e of )ourceTabeN is used. Follo#ing creates default "apping:

D%t%0%bleM%11ing c&stM%1 = c&stD2.0%bleM%11ings.2dd(-0%ble-/ -)ort*windC&stomers-); c&stM%1.Col&mnM%11ings.2dd( -Com1%ny)%me-/ -Com1%ny-); c&stM%1.Col&mnM%11ings.2dd( -Cont%ct)%me-/ -Cont%ct-); c&stM%1.Col&mnM%11ings.2dd( -Post%lCode-/ -O.PCode-); c&stD2.?ill(c&stDS);

7f )elect/o""and returns "ultiple tables* Fill #ill generate Table na"es #ith incre"ental na"es starting fro" specified na"e. ;se table "appings to "ap auto"aticall generated na"es to na"es #ant to use* e.g. follo#ing )elect/o""and returns t#o tables that #ill be na"ed /usto"ers and /usto"es3* "ap /usto"ers3 to Orders

c&stD2.0%bleM%11ings.2dd(-C&stomers5-/ -Orders-) c&stD2.?ill(c&stDS/ -C&stomers-)

Typed DataSets
)tandard Data)et = #ee5l t ped ! "ust convert data point fro" ob2ect to desired t pe T ped Data)et = strongl t ped 7nstance of class derived fro" Data)et /lass structure defined b -.+ sche"a file %-)D& defining table na"es and t pes ?

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

Dependence on -)D "eans onl use #here 5no# structure of data being used in advance /reate using Cenerate Dataset button in Data dialog bo4 ! generates -)D file and optionall adds instance of Data)et to designer

Lesson 3
i!!ing DataSet "it#out DataAdapter
? /reate Data)et progra""aticall * and provide it #ith structure D%t%Set myD%t%Set = new D%t%Set(); D%t%0%ble my0%ble = new D%t%0%ble(); myD%t%Set.0%bles.2dd(my0%ble); D%t%Col&mn 2cco&ntsCol&mn = new D%t%Col&mn(2cco&nts+); myD%t%Set.0%blesD$E.Col&mns.2dd(%cco&ntsCol&mn); D%t%7ow my7ow; my7ow = myD%t%Set.0%blesD$E.)ew7ow(); for(int i=$; . P StringCollection.Co&nt; iFF) : my7ow..temDco&nterE = StringCollection DiE; ; myD%t%Set.0%bles($).7ows.2dd(my7ow); Access Flat File and populate Data)et using progra""atic techni$ue outlined above <hen reading flat file "ust no deli"iters ! fre$uentl * or E or : bet#een colu"ns and ne#@line bet#een ro#s /reate Data)et around file structure D%t%Set myD%t%Set = new D%t%Set(); D%t%0%ble %0%ble = new D%t%0%ble(0%ble 5+); myD%t%Set.0%bles.2dd(%0%ble); D%t%Col&mn %Col&mn; for(int co&nter=$; co&nter PQ ;co&nterFF) : %Col&mn = new D%t%Col&mn(Col&mn F co&nter.0oStgring()); myd%t%Set.0%blesD0%ble 5+E.Col&mns.2dd (%Col&mn);
Use subject to our Ter"s and /onditions Written By 'oss Fruen

; System..O.Stre%m7e%der my7e%der = new System..O.Stre%m7e%der(C'((?ile.t8t+); String myString; w*ile (my7e%der.PeeN() R= S5) : myString = my7e%der.7e%d ine(); myD%t%Set.0%blesD0%ble 5+E.7ows.2dd (myString.S1lit(c*%r.P%rse(/+))); ;

Data Re!ation O$%ects


'epresents relationship bet#een t#o colu"ns in different tables #ithin Data)et /ontained in 'elations propert of Data)et /reate b specif ing na"e of Data'elation* parent colu"n and child colu"n D%t%7el%tion my7el%tion = new D%t%7el%tion(D%t% 7el%tion 5+/ col&mn5/ col&mnL); myD%t%Set.7el%tions.2dd(my7el%tion); ? ;se to retrieve parent and child ro#s b calling Cet/hild'o#s or CetParent'o# on Data'o# providing Data'elation as par" ?

D%t%s7owDE C*ild7ows; D%t%7ow P%rent7ow; @@ 7et&rn %ll c*ild rows of row 5 %s defined by C&stomersOrders C*ild7ows = myD%t%Set.0%blesDC&stomers+E.7owsD5E.<etC*ild7ows(C&stom ersOrders); @@ 7et&rn 1%rent of row 6 %s defined by C&stomersOrders P%rent7ow = myD%t%Set.0%blesDOrders+E.7owsD6E.<etP%rent7ow(C&stomers Orders);

Constraints
? <or5 closel #ith Data'elation ob2ects Define rules b #hich data added and "anipulated in DataTable ( t pes o ;ni$ue ! specifies colu"n%s& have no duplicate entries
Use subject to our Ter"s and /onditions Written By 'oss Fruen

Foreign Fe ! rules used to update child ro#s #hen parent edited /reate ;ni$ue /onstraint o Easiest is set ;ni$ue propert of Data'o# to true /an create ;ni$ue/onstraint and "anuall add to /onstraints collection Tni,&eConstr%int myConstr%int = new Tni,&eConstr%int(myD%t%7ow); myD%t%0%ble.Constr%ints.2dd(myConstr%int); o /an specif "ultiple colu"ns ?

D%t%Col&mnDE myCol&mns = new D%t%Col&mnDLE; myCol&mnsD$E = !m1loyees0%ble.Col&mnsD?irst)%me+E; myCol&mnsD$E = !m1loyees0%ble.Col&mnsD %st)%me+E; Tni,&eConstr%int myConstr%int = new Tni,&eConstr%int(myCol&mns); !m1loyees0%ble.Constr%ints.2dd(myConstr%int); ? /reate Foreign Fe /onstraint b specif ing parent and child colu"ns and adding to /onstraints collection of parent table ?oreignMeyConstr%int myConstr%int = new ?oreignMeyConstr%int(C&stomers0bl.Col&mnsDC&st omer.D+E/ Orders0bl.Col&mnsDC&stomer.D+E); C&stomers0bl.Constr%ints.2dd(myConstr%int); ForeignFe /onstraint has D rules e4posed as properties o ;pdate'ule ! enforce #hen parent updated Delete'ule ! enforce #hen parent deleted Accept'e2ect'ule ! enforce #hen Accept/hanges "ethod of DataTable to #hich constraint belongs is called ? )et D rules to one of follo#ing values %default = /ascade& o /ascade ! /hanges in parent cascaded to child ro#s None ! changes in parent have no effect on child ro#s. .a lead to child records referencing invalid parents )etDefault ! foreign 5e in child records set to its default value %see colu"ns DefaultBalue propert & )etNull ! foreign 5e in child table set to Null ! can result in invalid data #ithin children ?

Editing Data
? Data)et "aintain ( versions of itself o Original state
Written By 'oss Fruen

Use subject to our Ter"s and /onditions

/urrent state ? <hen ;pdate "ethod of DataAdapter called appropriate ;PDATE* 7N)E'T and Delete co""ands issued based on differences bet#een states /hanges "ade through data@bound controls auto"aticall reflected in relevant ro# /an progra""aticall add values to Data'o# b setting its 7te" propert %default propert ! no need to e4plicitl reference& myD%t%7owDLE = S1l&nge+; myD%t%7owDC&stomers+E = 9int*ro1+; ? /an roll@bac5 changes to Data'o# b calling 'e2ect/hanges "ethod%& myD%t%7ow.7eBectC*%nges(); ? /an accept changes b calling Accept/hanges%& "ethod. This over#rites the original version of the Data'o# #ith the edited version. Do not call before using ;pdate "ethod on DataAdapter* other#ise "eaningless ;PDATE co""ands #ill be issued. ?

/urrent ro# state available in 'o#)tate propert o ;nchanged ! original or not changed since Accept/hanges called .odified ! ro# edited since last Accept/hanges Added ! Ne#l created ro# added to Data'o#/ollection Deleted ! 'o# deleted using Data'o#.Delete "ethod Detached ! 'o# created but not part of an Data'o# collection

Updating Data$ase
? /op data bac5 to database using ;pdate "ethod of each DataAdapter ! optionall specif Data)et* DataTable or arra of Data'o#s as basis for update

myD%t%2d%1ter.T1d%te(); myOt*erD%t%2d%1ter.T1d%te(myD%t%0%ble); /an perfor" update #ithin transaction o /all 6eginTransaction of open /onnection ob2ect to obtain transaction E4ecute co""ands to be encapsulated b transaction /all /o""it on transaction ob2ect to accept* or 'ollbac5 to re2ect System.D%t%.OleDb.OleDb0r%ns%ction my0r%ns%ction = n&ll; try : myConnection.O1en(); ?

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

my0r%ns%ction = myConnection."egin0r%ns%ction(); U my0r%ns%ction.Commit(); ; c%tc*(!8ce1tion e8) : mytr%ns%ction.7ollb%cN(); ; fin%lly : myConnection.Close(); ;

&and!ing Update Errors


DataAdapter provides 'o#;pdate event that fires after update event but before e4ception thro#n ! opportunit to handle errors #ithout resource@ intensive e4ception bloc5s 'o#;pdate provides 'o#;pdatedEventArgs that is used to deter"ine error that has occurred and ho# to proceed o /o""and ! co""and to e4ecute #hen perfor"ing update Errors ! errors generated b Data Provider #hen co""and e4ecutes 'ecordsAffected ! nu"ber of records affected b e4ecution of co""and 'o# ! ro# updated )tatus @ ;pdate)tatus of co""and ? Deter"ine if error occurred b e4a"ining )tatus. o /ontinue ! no errors have occured ErrorsOccured ! error occurred #hile atte"pting to update this ro# )5ipAll'e"aining'o#s ! updates for current and subse$uent ro#s should be s5ipped )5ip/urrent'o# ! update for current ro# should be s5ipped* but rest of updates should proceed nor"all ? /an choose to handle error in 'o#;pdated event b setting )tatus propert to so"ething other than ErrorsOccured o Note* if set )tatus to /ontinue the DataAdapter #ill ignore the error and continue but unpredictable results "a arise %safer to use )5ipAll'e"aining'o#s or )5ip/urrent'o#& 7f )tatus re"ains ErrorsOccured an e4ception thro#n private void " DataAdapterG'o#;pdated% ob2ect sender* ) ste".Data.)$l/lient.)$l'o#;pdatedEventArgs e& H if%e.)tatus == ;pdate)tatus.ErrorsOccured& H I e.)tatus = ;pdate)tatus.)5ip/urrent'o#E
Use subject to our Ter"s and /onditions Written By 'oss Fruen

J J

Lesson 4
Data Binding
? 'elationship bet#een data provider and consu"er E4a"ple = Te4t6o4 #hich displa s colu"n in data source at current ro#. As ro# changes* the value displa ed changes

Data Providers
? Provides data to bound properties and controls Note ! not a DataProvider %co"ponents providing disconnected database access& An ob2ect i"ple"enting 7+ist can be data provider %includes arra s and collections& .anage data currenc %i.e. current record& through /urrenc .anager ob2ect

Data Consumers
? /an bind an run@ti"e accessible propert of an control to a data source T#o t pes of binding o )i"ple ! binds one record at a ti"e to a control /o"ple4 ! binds "ultiple records si"ultaneousl to a control* e.g. bind +ist6o4 to a colu"n in DataTable and it #ill displa all "e"bers of that colu"n

Create Simp!e $ound contro!


? ;se Data6indings propert %instance of /ontrol6indings/ollection& Displa ed as node in Properties #indo#* e4pands to sho# properties that are co""onl data bound To bind propert clic5 bo4 ne4t to it in Data6indings node and select desired provider %Data)ets and DataBie#s can be e4panded to sho# DataTables that can be e4panded to list available colu"ns 7f propert not listed in Data6indings clic5 Advanced bo4 follo#ed b Elipses %I& #hich lists all run ti"e available properties At run@ti"e can add* re"ove or clear data binding info b setting appropriate "e"ber of Data6indings collection 6ind propert using Data6indings.Add "ethod passing in propert na"e* data source to bind to and "e"ber of data source to bind to 0e8t"o85.D%t%"indings.2dd(0e8t+/ D%t%Set5.C&stomers/ C&stomer.D+); ? 7f binding to source #ithout "ultiple data "e"bers* e.g. collection or arra * set third par" to blan5 %89&
Written By 'oss Fruen

Use subject to our Ter"s and /onditions

Data Currency
? Ever data source "anages navigation using a /urrenc .anager ob2ect Data source = 3 or ( D store %DataTable* DataBie#* arra * collection& Data)et contains "an DataTables* thus "an data sources /urrenc .anager 5eeps trac5 of current record for its particular data source For" "a have "ultiple /urrenc .anagers associated #ithin its data sources* "anages these through the 6inding/onte4t /an use 6inding/onte4t to "anage position of current record for each data source t*is."indingConte8tDD%t%Set5.C&stomersE.Position = $; t*id.bindingConte8tDD%t%Set5.C&stomersE.PositionFF; ? .Net #ill not per"it Position propert to be set out of range /hange of Position propert causes Position/hanged event to be fired ! use to provide additional processing on "ove %e.g. to indicate #hen range li"it reached&

Comp!e' Binding
)o"e controls %e.g. +ist6o4* /o"bo6o4* DataCrid& can be bound to "ore than one record si"ultaneousl ;suall used to displa choices /reate b setting Data)ource propert * either at design ti"e or via code )o"e controls* such as +ist6o4 and /o"bo6o4* "ust be bound to single colu"n ! do this b setting Displa .e"ber propert Combo"o85.D%t%So&rce = D%t%Set5.C&stomers; Combo"o85.Dis1l%yMember = C&stomer.D+; ?

i!tering and Sorting


? DataBie# per"its #or5ing #ith subset of data held #ithin DataTable DataBie# provides "ethods for sorting and filtering data DataBie# can update DataTable it represents ? /reate DataBie# ! can provide DataTable at construction* or later via Table propert D%t%4iew myD%t%4iew = new D%t%4iew(myD%t%0%ble); Or D%t%4iew myD%t%4iew = new D%t%4iew(); myD%t%4iew.0%ble = myD%t%0%ble; ? /an create at design ti"e. Drag DataBie# fro" Data tab of Toolbo4 to designer and set its Table propert in the properties #indo#

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

6ind controls to DataBie# b setting the Data6indings properties in the Properties #indo# )orting acco"plished b setting )ort propert to appropriate colu"n na"e %or "ultiple colu"ns separated b 8*9&. To sort descending append DE)/ to na"e myD%t%4iew.Sort = C&stomer.D+; myOt*er4iew.Sort = St%te/ City+; myDesc4iew.Sort = St%te D!SC/ City+; ? Filter data through 'o#Filter propert that ta5es string e4pression to be evaluated #hen selecting records. 6uild co"ple4 e4pressions using AND* O' and NOT together #ith arith"etic* concatenation and relational operations. 7N and +7FE operators per"it searches for specific strings. myD%t%4iew.7ow?ilter = City = VSe%ttleI+; myD%t%4iew.7ow?ilter = City = VDes MoinesI 2)D ()O0 St%te =I.2I)+; myD%t%4iew.7ow?ilter = Price A5.$WX P= 6$$+; myD%t%4iew.7ow?ilter = City .) (VSe%ttleI/ V0%com%I/ V"l%ineI); myD%t%4iew.7ow?ilter = City ? .M! VSeAtYeI+;

Additional filtering provided b 'o#)tate propert that can ta5e 3 %or "ore& of the follo#ing values o ;nchanged ! displa s ro#s that have not been changed Added ! displa s ro#s that have been added Deleted ! displa s ro#s that have been deleted Origianl'o#s ! original ro#s including unchanged and deleted ro#s /urrent'o#s ! current ro#s %including added* "odified and unchanged& .odified/urrent ! .odified version of original data .odifiedOrigianl ! Original version DataBie# has D properties that deter"ine if underl ing data can be edited. 6 default full editable* den access b setting appropriate propert to false o Allo#Delete ! is deletion of ro#s in underl ing DataTable allo#ed Allo#Edit ! is editing of ro#s in underl ing DataTable allo#ed Allo#Ne# ! can ro#s be added to underl ing DataTable ? DataBie#.anager is to Data)et #hat DataBie# is to DataTable. DataBie#.anager associated #ith Data)et and "anages DataBie# ob2ects for tables contained #ithin Data)et D%t%4iewM%n%ger myM%n%ger = new D%t%4iewM%n%ger(myD%t%Set);
Use subject to our Ter"s and /onditions Written By 'oss Fruen

D%t%4iewM%n%ger myOt*erM%n%ger = new D%t%4iewM%n%ger(); myOt*erM%n%ger.D%t%Set = myOt*erD%t%Set; ? .anage 'o#Filter* )ort* etc. through DataBie#)ettings collection

@@ Set 7ow?ilter 1ro1erty of D%t%4iew %ssoci%ted @@ wit* C&stomers t%ble myD%t%4iewM%n%ger.D%t%4iewSettingsDC&stomers+E .7ow?ilter = St%te = V92I+; ? /an retievde DataBie#s via /reateDataBie# "ethod ! re$uires reference to DataTable

D%t%4iew myD%t%4iew; myD%t%4iew = myD%t%4iewM%n%ger.Cre%teD%t%4iew(D%t%Set5.0%blesD$E) ;

Lesson 5
Retrieving (m!Reader )rom S*!Command
-"l'eader analogous to Data'eader class ! read onl * for#ard onl access to -.+ returned b $uer -"l'eader %li5e Data'eader& re$uires e4clusive use of connection )$l/o""and provides E4ecute-"l'eader "ethod to retrieve -.+'eader ob2ect that e4posed data fro" )$l/o""and as -.+ ro#s ),+ $uer e4ecuted b )$l/o""and "ust contain FO' -.+ clause Al#a s close -"l'eader to free /onnection System.Zml.Zml7e%der my7e%der; S,lComm%nd mySK Comm%nd = new S,lComm%nd(S! !C0 A ?7OM C&stomers ?O7 ZM 2T0O/ ZM D202+/ S,lConnection5); S,lConnection5.O1en(); my7e%der = mySK Comm%nd.!8ec&teZml7e%der(); w*ile(my7e%der.7e%d()) : @@ 9rite content %nd m%rN&1 of node %nd its @@ c*ildren Console.9rite ine(my7e%der.7e%dO&terZml()); ; my7e%der.Close();
Use subject to our Ter"s and /onditions Written By 'oss Fruen

S,lConnection5.Close();

Reading (+, into DataSet


? ;se Data)et.'ead-"l to specif -.+ file* strea"* -"l'eader or Te4t'eader ;se Data)et.'ead-"l)che"a to create Data)et #ith specified structure but no data

-riting (+, )rom DataSet


? ;se Data)et.<rite-"l to e4port data in -.+ for"at ;se Data)et.<rite-"l)che"a to e4port structure of Data)et #ithout its data

(m!DataDocument
? 7n "e"or representation of -.+ data <or5s closel #ith its associated Data)et ! access to it via -"lDataDocu"ent.Data)et propert /an be "anipulated b <D/ Docu"ent Ob2ect .odel %DO.& )erves as source for E4tensible )t le )heet Transfor"ations %-)+T& <hen create can provide associated Data)et to constructor ZmlD%t%Doc&ment myDoc&ment = new ZmlD%t%Doc&ment(myD%t%Set); 7f no Data)et provided to constructor then ne#* e"pt one created auto"aticall To load data into -"lDataDocu"ent "ust first call 'ead-"l)che"a%& "ethod on Data)et. Then call +oad%& "ethod on -"lDataDocu"ent ZmlD%t%Doc&ment mydoc&ment = new ZmlD%t%Doc&ment(); myDoc&ment.D%t%Set.7e%dZmlSc*em%(C'((myZml.8ml+); myDoc&ment. o%d(C'((myZml.8ml+); ?

(S,T Trans)ormations
? Transfor" -.+ data into different for"ats* e.g. KT.+ -slTransfor" class provided for this purpose First load st le sheet into class via -slTransfor".+oad%& /all -slTransfor".Transfor"%& o Par" 3 = ob2ect to transfor" Par" ( = an par"s re$uired b st lesheet* other#ise N;++ Par" D = ob2ect to receive output %)trea"* Te4t<riter or -"l<riter& Zml.Zsl.Zsl0r%nsform my0r%nsform = new Zml.Zsl.Zsl0r%nsform(); my0r%nsform. o%d(C'((myStyle.8sl+); System..O.Stre%m9riter my9riter = new
Use subject to our Ter"s and /onditions Written By 'oss Fruen

System..O.Stre%m9riter(myfile.t8t+); my0r%nsform.0r%nsform(myDoc&ment/ n&ll/ my9riter);

Use subject to our Ter"s and /onditions

Written By 'oss Fruen

Das könnte Ihnen auch gefallen