转: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;}
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;}
TheEmployeeclassexposesEmployeeID,FirstName,andLastNameproperties:
.cf{font-family:CourierNew;font-size:10pt;color:black;}.cl{margin:0px;}.cb1{color:blue;}.cb2{color:#2b91af;}
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;}
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!
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!
相关文章推荐
- Bulk Operations Using Oracle Data Provider for .NET (ODP.NET) 转载
- Interaction between C# Application and Oracle through Custom Object
- csharp: Oracle Stored Procedure DAL using ODP.NET
- Making Best Out Of Oracle Databases Using ODP.net - Part I
- Using CoCreateObjectDotNet to Access and Use .NET Assemblies in InstallScript
- csharp: Oracle Stored Procedure DAL using ODP.NET
- Making best out of Oracle batabases using ODP.net - Part 2
- 论文笔记:Structure Inference Net: Object Detection Using Scene-Level Context and Instance-Level Relationships
- Building a Distributed Object System with .NET and J2EE Using IIOP.NET
- csharp: Oracle Stored Procedure DAL using ODP.NET
- ORACLE HANDBOOK系列之六:ODP.NET与复杂的PL/SQL数据类型(Using ODP.NET To Deal With Complex PLSQL Data Types)
- Querying Active Directory using .NET classes and LDAP queries(http://www.codeproject.com/dotnet/activedirquery.asp)
- ODP.NET 之访问 Oracle 数据库
- JsonHelper developed by using Newtonsoft.Json.NET, Deserialize to <T> object , XmlToJson/JsonToXml, QuoteName by using JToken Path.
- 【ASP.NET Step by Step】之六 Programmatically Setting the ObjectDataSource's Parameter Values
- 《.NET 2.0模式开发实战》Foundations of Object-Oriented Programming Using .NET 2.0 Patterns
- Object-Oriented Analysis and Design Using UML 翻译与学习 (四)
- Sensor fusion and input representation for time series classification using deep nets
- Model View Controller (MVC) Using C#, Delegates and Events in .NET
- A Beginner Tutorial for Writing Simple COM/ATL DLL and Using it with .NET