您的位置:首页 > 数据库 > Oracle

转:Oracle之ODP.NET: Using ObjectDataSource, Ref Cursors, and Custom Classes

2010-04-29 12:43 603 查看

WhencreatingapplicationssuchasASP.NETapplications,oftentimestheapplicationissplitintovariousconceptualorphysicallayers.Therearetypicallythreelayersinsuchaschemeandtheymaygenerallybebrokenoutasthepresentationlayer,thebusinesslogiclayer,andthedataaccesslayer.Dependingonyourspecificneeds,standards,etc.sometimesthelayersmaybefoldedintoasinglelayer.Forexample,youmaychoosetoimplementyourbusinesslogicusingstoredproceduresandco-locatethebusinesslogiclayerwiththedataaccesslayerinthedatabase.

Thereareplussesandminuses(ortrade-offs)associatedwiththearchitecturaldecisionsforanapplicationandIdon'tintendtoproposeanyonebeingbetterthananother.Instead,IwouldliketoillustrateasimplemethodofcreatingapresentationlayerandadataaccesslayerusingObjectDataSourcecontrols,RefCursors,andcustomclasses.Thereisnobusinesslogiclayerinthissimpleexampleasitwouldmerelybeaproxyorwrapperofthedataaccesslayer.Thedataaccesslayerreturnscollectionsofcustomclassestothepresentationlayerusingthe.NETFramework2.0System.Collections.Generic.Listgenerictype.

ThesampleusesasimpleASP.NETpage:





InordertoprovidethedataaccesslayerwithdatafromthedatabasethefollowingPL/SQLPackageandPackageBodyshouldbecreatedastheHRuserinthedatabaseyouplantouse:

.cf{font-family:CourierNew;font-size:10pt;color:black;}.cl{margin:0px;}

createorreplacepackagehuman_resourcesas
procedureget_departments(p_departmentsoutsys_refcursor);
procedureget_department_employees(p_department_idinemployees.department_id%type,
p_employeesoutsys_refcursor);
end;
/
createorreplacepackagebodyhuman_resourcesas
procedureget_departments(p_departmentsoutsys_refcursor)is
begin
openp_departmentsfor
selectdepartment_id,
department_name
fromdepartments
orderbydepartment_name;
end;
procedureget_department_employees(p_department_idinemployees.department_id%type,
p_employeesoutsys_refcursor)is
begin
openp_employeesfor
selectemployee_id,
first_name,
last_name
fromemployees
wheredepartment_id=p_department_id
orderbylast_name,
first_name;
end;
end;
/


ThissampleusesasingleASP.NETwebpage(default.aspx)andthreeC#codefiles:

Department.cs--thedepartmentclassinthe.NETcode(get_departmentsprocedure)

Employee.cs--theemployeeclassinthe.NETcode(get_department_employeesprocedure)

EmployeeDAL.cs--thedataaccesslayer.ThiscodeaccessesthedatabaseandreturnsthecollectionofeitherDepartmentorEmployeeobjectstothepresentationlayer.

ThecomponentsthatmakeuptheVisualStudioSolutionareasfollowsintheSolutionExplorer:



AswiththePL/SQLcodeinthedatabase,theC#codeissimpleandomitsmanynormalfeaturessuchaserrorhandling.Inaddition,theclassesonlyimplement"get"functionalityfortheclasspropertiesinordertokeepthecodeasshortandassimpleaspossible.

TheDepartmentclasshasDepartmentIDandDepartmentNamepropertiesandisasfollows:

.cf{font-family:CourierNew;font-size:10pt;color:black;}.cl{margin:0px;}.cb1{color:blue;}.cb2{color:#2b91af;}

publicclassDepartment{
privateint_department_id;
privatestring_department_name;
publicintDepartmentID{
get{
return_department_id;
}
}
publicstringDepartmentName{
get{
return_department_name;
}
}
publicDepartment(intDepartmentID,stringDepartmentName){
_department_id=DepartmentID;
_department_name=DepartmentName;
}
}


TheEmployeeclassexposesEmployeeID,FirstName,andLastNameproperties:

.cf{font-family:CourierNew;font-size:10pt;color:black;}.cl{margin:0px;}.cb1{color:blue;}.cb2{color:#2b91af;}

publicclassEmployee{
privateint_employee_id;
privatestring_first_name;
privatestring_last_name;
publicintEmployeeID{
get{
return_employee_id;
}
}
publicstringFirstName{
get{
return_first_name;
}
}
publicstringLastName{
get{
return_last_name;
}
}
publicEmployee(intEmployeeID,stringFirstName,stringLastName){
_employee_id=EmployeeID;
_first_name=FirstName;
_last_name=LastName;
}
}


TheEmployeesDALclasshandlesconnectingtothedatabase,executingthestoredprocedures,buildingthecollectionofobjects,andreturningthoseobjectstothecaller:

.cf{font-family:CourierNew;font-size:10pt;color:black;}.cl{margin:0px;}.cb1{color:blue;}.cb2{color:#2b91af;}.cb3{color:#a31515;}

publicclassEmployeesDAL{
privatestaticstringconstr="UserId=hr;Password=hr;DataSource=lt10gr2;Enlist=false";
publicList<Department>GetDepartments()
{
OracleConnectioncon=newOracleConnection(constr);
con.Open();
OracleCommandcmd=con.CreateCommand();
cmd.CommandText="human_resources.get_departments";
cmd.CommandType=CommandType.StoredProcedure;
OracleParameterp_ref_cur=newOracleParameter();
p_ref_cur.OracleDbType=OracleDbType.RefCursor;
p_ref_cur.Direction=ParameterDirection.Output;
cmd.Parameters.Add(p_ref_cur);
OracleDataReaderdr=cmd.ExecuteReader();
List<Department>Departments=newList<Department>();
while(dr.Read())
{
DepartmentthisDept=newDepartment(dr.GetInt32(0),dr.GetString(1));
Departments.Add(thisDept);
}
dr.Dispose();
cmd.Dispose();
con.Dispose();
returnDepartments;
}
publicList<Employee>GetDepartmentEmployees(intp_department_id){
OracleConnectioncon=newOracleConnection(constr);
con.Open();
OracleCommandcmd=con.CreateCommand();
cmd.CommandText="human_resources.get_department_employees";
cmd.CommandType=CommandType.StoredProcedure;
OracleParameterp_dept_id=newOracleParameter();
p_dept_id.OracleDbType=OracleDbType.Decimal;
p_dept_id.Value=p_department_id;
OracleParameterp_ref_cur=newOracleParameter();
p_ref_cur.OracleDbType=OracleDbType.RefCursor;
p_ref_cur.Direction=ParameterDirection.Output;
cmd.Parameters.Add(p_dept_id);
cmd.Parameters.Add(p_ref_cur);
OracleDataReaderdr=cmd.ExecuteReader();
List<Employee>Employees=newList<Employee>();
while(dr.Read()){
EmployeethisEmp=newEmployee(dr.GetInt32(0),dr.GetString(1),dr.GetString(2));
Employees.Add(thisEmp);
}
p_dept_id.Dispose();
p_ref_cur.Dispose();
dr.Dispose();
cmd.Dispose();
con.Dispose();
returnEmployees;
}
}


TheASP.NETpageconsistsofsimpletexttodenotetheDepartmentdatawhichispresentedinaDropDownList,aGridViewcontroltodisplaytheemployeesintheselecteddepartment,andtwoObjectDataSourcecontrols.ThisistheDefault.aspxpageatdesigntime:





ToconfiguretheObjectDataSource1controlselect"ConfigureDataSource..."fromthequicktasksconfiguration:

Chooseabusinessobject:



ClickNextandthenselecttheGetDeparmentsmethodfortheSELECTtabandclickFinish:



Next,configuretheDropDownList1controlwhichdisplaystheDepartmentinformation.EnsurethattheEnableAutoPostBackoptionischeckedinthequicktaskconfigurationorthattheAutoPostBackpropertyisTrueinthePropertieswindow.ToconfiguretheDataSourceforthecontrol,select"ChooseDataSource..."fromthequicktaskconfigurationandcompleteasfollows:



TheObjectDataSource2controlshouldbeconfigurednextbyclickingthe"ConfigureDataSource..."optiononthequicktasksconfiguration:

Again,chooseaBusinessObject:



FollowedbytheGetDepartmentEmployeesmethodfortheSELECTtab:



TheGetDepartmentEmployeesmethodtakesaninputparameterthatspecifiestheDepartmentIDforwhichemployeesshouldberetrieved.Therefore,itisnecessarytoconfiguretheparameterinputvaluesothattheDepartmentIDselectedbytheuserintheDropDownList1controlispassedtotheGetDepartmentEmployeesmethod:



Finally,associatetheObjectDataSource2controlwiththeGridView1controlbychoosing"ObjectDataSource2"inthe"ChooseDataSource"drop-downlistfortheGridViewquicktasks.Ofcourseyoumayalsochoosetoenablepagingandformattingasyoudesire.

NowthatboththeDropDownList1andtheGridView1webcontrolsare"hookedup"totheirrespectiveObjectDataSourcecontrols,andtheObjectDataSourcecontrolsare,inturn,configuredtoexposethedatareturnedbytheEmployeesDALclass,itistimetorunthesamplepage!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐