asp databasetutorial

  • View
    212

  • Download
    0

Embed Size (px)

DESCRIPTION

asp databasetutorial

Transcript

  • Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.NETintheWorkingwithDatainASP.NET2.0sectionoftheASP.NETsiteathttp://www.asp.net/learn/dataaccess/default.aspx.

    WorkingwithDatainASP.NET2.0::CreatingaDataAccessLayer

    IntroductionAswebdevelopers,ourlivesrevolvearoundworkingwithdata.Wecreatedatabasestostorethedata,codetoretrieveandmodifyit,andwebpagestocollectandsummarizeit.ThisisthefirsttutorialinalengthyseriesthatwillexploretechniquesforimplementingthesecommonpatternsinASP.NET2.0.We'llstartwithcreatingasoftwarearchitecture composedofaDataAccessLayer(DAL)usingTypedDataSets,aBusinessLogicLayer(BLL)thatenforcescustombusinessrules,andapresentationlayercomposedofASP.NETpagesthatshareacommonpagelayout.Oncethisbackendgroundworkhasbeenlaid,we'llmoveintoreporting,showinghowtodisplay,summarize,collect,andvalidatedatafromawebapplication.Thesetutorialsaregearedtobeconciseandprovidestepbystepinstructionswithplentyofscreenshotstowalkyouthroughtheprocessvisually.EachtutorialisavailableinC#andVisualBasicversionsandincludesadownloadofthecompletecodeused.(Thisfirsttutorialisquitelengthy,buttherestarepresentedinmuchmoredigestiblechunks.)

    Forthesetutorialswe'llbeusingaMicrosoftSQLServer2005ExpressEdition versionoftheNorthwinddatabaseplacedintheApp_Datadirectory.Inadditiontothedatabasefile,theApp_DatafolderalsocontainstheSQLscriptsforcreatingthedatabase,incaseyouwanttouseadifferentdatabaseversion.ThesescriptscanbealsobedownloadeddirectlyfromMicrosoft,ifyou'dprefer.IfyouuseadifferentSQLServerversionoftheNorthwinddatabase,youwillneedtoupdatetheNORTHWNDConnectionStringsettingintheapplication'sWeb.configfile.ThewebapplicationwasbuiltusingVisualStudio2005ProfessionalEditionasafilesystembasedWebsiteproject.However,allofthetutorialswillworkequallywellwiththefreeversionofVisualStudio2005, VisualWebDeveloper.

    Inthistutorialwe'llstartfromtheverybeginningandcreatetheDataAccessLayer(DAL),followedbycreatingtheBusinessLogicLayer(BLL)inthesecondtutorial,andworkingonpagelayoutandnavigationinthethird.Thetutorialsafterthethirdonewillbuilduponthefoundationlaidinthefirstthree.We'vegotalottocoverinthisfirsttutorial,sofireupVisualStudioandlet'sgetstarted!

    Step1:CreatingaWebProjectandConnectingtotheDatabaseBeforewecancreateourDataAccessLayer(DAL),wefirstneedtocreateawebsiteandsetupourdatabase.StartbycreatinganewfilesystembasedASP.NETwebsite.Toaccomplishthis,gototheFilemenuandchooseNewWebSite,displayingtheNewWebSitedialogbox.ChoosetheASP.NETWebSitetemplate,settheLocationdropdownlisttoFileSystem,chooseafoldertoplacethewebsite,andsetthelanguagetoC#.

    1 of34

  • Figure1:CreateaNewFileSystemBasedWebSite

    ThiswillcreateanewwebsitewithaDefault.aspxASP.NETpageandanApp_Datafolder.

    Withthewebsitecreated,thenextstepistoaddareferencetothedatabaseinVisualStudio'sServerExplorer.ByaddingadatabasetotheServerExploreryoucanaddtables,storedprocedures,views,andsoonallfromwithinVisualStudio.YoucanalsoviewtabledataorcreateyourownquerieseitherbyhandorgraphicallyviatheQueryBuilder.Furthermore,whenwebuildtheTypedDataSetsfortheDALwe'llneedtopointVisualStudiotothedatabasefromwhichtheTypedDataSetsshouldbeconstructed.Whilewecanprovidethisconnectioninformationatthatpointintime,VisualStudioautomaticallypopulatesadropdownlistofthedatabasesalreadyregisteredintheServerExplorer.

    ThestepsforaddingtheNorthwinddatabasetotheServerExplorerdependonwhetheryouwanttousetheSQLServer2005ExpressEditiondatabaseintheApp_DatafolderorifyouhaveaMicrosoftSQLServer2000or2005databaseserversetupthatyouwanttouseinstead.

    UsingaDatabaseintheApp_DataFolder

    IfyoudonothaveaSQLServer2000or2005databaseservertoconnectto,oryousimplywanttoavoidhavingtoaddthedatabasetoadatabaseserver,youcanusetheSQLServer2005ExpressEditionversionoftheNorthwinddatabasethatislocatedinthedownloadedwebsite'sApp_Datafolder(NORTHWND.MDF).

    AdatabaseplacedintheApp_DatafolderisautomaticallyaddedtotheServerExplorer.AssumingyouhaveSQLServer2005ExpressEditioninstalledonyourmachineyoushouldseeanodenamedNORTHWND.MDFintheServerExplorer,whichyoucanexpandandexploreitstables,views,storedprocedure,andsoon(seeFigure2).

    TheApp_DatafoldercanalsoholdMicrosoftAccess.mdbfiles,which,liketheirSQLServercounterparts,areautomaticallyaddedtotheServerExplorer.Ifyoudon'twanttouseanyoftheSQLServeroptions,youcanalwaysdownloadaMicrosoftAccessversionoftheNorthwinddatabasefileanddropintotheApp_Datadirectory.Keepinmind,however,thatAccessdatabasesaren'tasfeaturerichasSQLServer,andaren'tdesignedtobeusedinwebsitescenarios.Furthermore,acoupleofthe35+tutorialswillutilizecertaindatabaselevelfeaturesthataren'tsupportedbyAccess.

    2 of34

  • ConnectingtotheDatabaseinaMicrosoftSQLServer2000or2005DatabaseServerAlternatively,youmayconnecttoaNorthwinddatabaseinstalledonadatabaseserver.IfthedatabaseserverdoesnotalreadyhavetheNorthwinddatabaseinstalled,youfirstmustaddittodatabaseserverbyrunningtheinstallationscriptincludedinthistutorial'sdownloadorbydownloadingtheSQLServer2000versionofNorthwindandinstallationscriptdirectlyfromMicrosoft'swebsite.

    Onceyouhavethedatabaseinstalled,gototheServerExplorerinVisualStudio,rightclickontheDataConnectionsnode,andchooseAddConnection.Ifyoudon'tseetheServerExplorergototheView/ServerExplorer,orhitCtrl+Alt+S.ThiswillbringuptheAddConnectiondialogbox,whereyoucanspecifytheservertoconnectto,theauthenticationinformation,andthedatabasename.OnceyouhavesuccessfullyconfiguredthedatabaseconnectioninformationandclickedtheOKbutton,thedatabasewillbeaddedasanodeunderneaththeDataConnectionsnode.Youcanexpandthedatabasenodetoexploreitstables,views,storedprocedures,andsoon.

    Figure2:AddaConnectiontoYourDatabaseServer'sNorthwindDatabase

    Step2:CreatingtheDataAccessLayerWhenworkingwithdataoneoptionistoembedthedataspecificlogicdirectlyintothepresentationlayer(inawebapplication,theASP.NETpagesmakeupthepresentationlayer).ThismaytaketheformofwritingADO.NETcodeintheASP.NETpage'scodeportionorusingtheSqlDataSourcecontrolfromthemarkupportion.Ineithercase,thisapproachtightlycouplesthedataaccesslogicwiththepresentationlayer.Therecommendedapproach,however,istoseparatethedataaccesslogicfromthepresentationlayer.ThisseparatelayerisreferredtoastheDataAccessLayer,DALforshort,andistypicallyimplementedasaseparateClass

    3 of34

  • Libraryproject.Thebenefitsofthislayeredarchitecturearewelldocumented(seethe"FurtherReadings"sectionattheendofthistutorialforinformationontheseadvantages)andistheapproachwewilltakeinthisseries.

    Allcodethatisspecifictotheunderlyingdatasource suchascreatingaconnectiontothedatabase,issuingSELECT,INSERT,UPDATE,andDELETEcommands,andsoonshouldbelocatedintheDAL.Thepresentationlayershouldnotcontainanyreferencestosuchdataaccesscode,butshouldinsteadmakecallsintotheDALforanyandalldatarequests.DataAccessLayerstypicallycontainmethodsforaccessingtheunderlyingdatabasedata.TheNorthwinddatabase,forexample,hasProductsandCategoriestablesthatrecordtheproductsforsaleandthecategoriestowhichtheybelong.InourDALwewillhavemethodslike:

    l GetCategories(), whichwillreturninformationaboutallofthecategoriesl GetProducts(),whichwillreturninformationaboutalloftheproductsl GetProductsByCategoryID(categoryID),whichwillreturnallproductsthatbelongtoaspecifiedcategory

    l GetProductByProductID(productID),whichwillreturninformationaboutaparticularproduct

    Thesemethods,wheninvoked,willconnecttothedatabase,issuetheappropriatequery,andreturntheresults.Howwereturntheseresultsisimportant.ThesemethodscouldsimplyreturnaDataSetorDataReaderpopulatedbythedatabasequery,butideallytheseresultsshouldbereturnedusingstronglytypedobjects.Astronglytypedobjectisonewhoseschemaisrigidlydefinedatcompiletime,whereastheopposite,alooselytypedobject,isonewhoseschemaisnotknownuntilruntime.

    Forexample,theDataReaderandtheDataSet(bydefault)arelooselytypedobjectssincetheirschemaisdefinedbythecolumnsreturnedbythedatabasequeryusedtopopulatethem.ToaccessaparticularcolumnfromalooselytypedDataTableweneedtousesyntaxlike:DataTable.Rows[index]["columnName"].TheDataTable'sloosetypinginthisexampleisexhibitedbythefactthatweneedtoaccessthecolumnnameusingastringorordinalindex.AstronglytypedDataTable,ontheotherhand,willhaveeachofitscolumnsimplementedasproperties,resultingincodethatlookslike:DataTable.Rows[index].columnName.

    Toreturnstronglytypedobjects,developerscaneithercreatetheirowncustombusinessobjectsoruseTypedDataSets.Abusinessobjectisimplementedbythedeveloperasaclasswhosepropertiestypicallyreflectthecolumnsoftheunderlyingdatabasetablethebusinessobjectrepresents.ATypedDataSetisaclassgeneratedforyoubyVisualStudiobasedonadatabaseschemaandwhosemembersarestronglytypedaccordingtothisschema.TheTypedDataSetitselfconsistsofclassesthatextendtheADO.NETDataSet,DataTable,andDataRowclasses.InadditiontostronglytypedDataTables,TypedDataSetsnowalsoincludeTableAdapters,whichareclasseswithmethodsforpopulatingtheDataSet'sDataTablesandpropagatingmodificationswithintheDataTablesbacktothedatabase.

    Note:FormoreinformationontheadvantagesanddisadvantagesofusingTypedDataSetsversuscustombusinessobjects,refertoDesigningDataTierComponentsandPassingDataThroughTiers.

    We'llusestronglytypedDataSetsforthesetutorials'architecture.Figure3illustratestheworkflowbetweenthedifferentlayersofanapplicationthatusesTypedDataSets.

    4 of34

  • Figure3:AllDataAccessCodeisRelegatedtotheDAL

    CreatingaTypedDataSetandTableAdapterTobegincreatingourDAL,westartbyaddingaTypedDataSettoourproject.Toaccomplishthis,rightclickontheprojectnodeintheSolutionExplorerandchooseAddaNewItem.SelecttheDataSetoptionfromthelistoftemplatesandnameitNorthwind.xsd.

    Figure4:ChoosetoAddaNewDataSettoYourProject

    AfterclickingAdd,whenpromptedtoaddtheDataSettotheApp_Codefolder,chooseYes.TheDesignerfortheTypedDataSetwillthenbedisplayed,andtheTableAdapterConfigurationWizardwillstart,allowingyoutoaddyourfirstTableAdaptertotheTypedDataSet.

    ATypedDataSetservesasastronglytypedcollectionofdataitiscompo