開放源碼的對象關係映射工具ORM.NET 查詢表 調用預存程序 增加自訂代碼

來源:互聯網
上載者:User
Lookup表

在ORM.NET Object Browser中指定表是lookup表,如所示

Lookup表明此表的資料是唯讀,不會產生任何的新增,刪除對象方法(Add[Object], New[Object], or Delete[Object]),列的屬性也不包含Set屬性。因此,Lookup表是用來表示static的資料,不會發生變化的資料。這樣,ORM.NET架構會cache緩衝它的值以改善效能。請看下面的代碼

// Create a new Lookup object – a sub-classed DataManagerLookups lookup = new Lookups(Config.Dsn);// find a specific course and assign a local object referenceCourse course = lookup.Courses.FindByClassName("History 101");// Display some property information about the Course retrieved from the cached Lookup objectConsole.WriteLine("Course " + course.ClassName + " " + course.ID);

下面的例子是示範collection的用法,尋找建立課程日期大於2002/11/06

// Assign a local Course CollectionCourseCollection courses = lookup.Courses;// loop through each record in the Course tableforeach(Course c in courses)  Console.WriteLine("Course Name: " + c.ClassName);//Create new Course collection with filter applied on the DateCreated propertyCourseCollection oldcourses = courses.FilterByDateCreated(DateTime.Parse("11/06/2002"));
 

下面的代碼,示範從Lookup中擷取資料

Lookups lookups = new Lookups(Config.Dsn);Schedule s = dm.NewSchedule();  // Create a new Schedule object// assign the Schedule object to the desired Course object (Parent)s.Course = lookups.Courses.FindByClassName("History 101"); //.. add the rest of the schedule informationdm.CommitAll(); // create the Schedule object with the Parent Course information

Lookup表的另一個作用是用來棒定到ASP.NET DropDownList,請看程式碼範例,代碼簡潔

Lookups lookups = new Lookups(Config.Dsn);// Courses is set as the DataSource - Courses is returned sorted by ID in ascending order.DropDownListCourses.DataSource = lookups.Courses.SortByID(SortDirection.Ascending);DropDownListCourses.DataBind();  // bind the data source
 

如果需要更新Lookup的值,比如在單獨的維護資料管理程式中,可以調用Lookup.ReRefreshLookups()來重新整理cache,重新擷取lookup資料。

 

調用預存程序 Working with Stored Procedures

使用ORM.NET的好處之一是,可以通過一套代碼,運行在多種資料庫平台中(雖然ORM.NET當前只支援SQL Server),所以盡量少用與特定資料庫相關的方式,比如預存程序。如果是在系統維護過程中,暫時無法移除對現有的預存程序的依賴,ORM.NET也提供了方法以訪問預存程序。

請看下面的SQL Server預存程序定義

ALTER PROC spGetContactDetails@LastName varchar(50),@City varchar(50) OUTPUT,@State varchar(50) OUTPUTASSELECT @City=City, @State=state              FROM Teacher t, Contact c              WHERE  t.FKContactId=c.Id     AND   LastName=@LastName

ORM.NET架構會自動產生.NET代碼封裝對它的訪問,.NET代碼如下

DataManager dm = new DataManager(Config.Dsn);string CityName = "";              // define and initialize SQL Output paramsstring StateName = "";// Pass Input and Output parameters to the Stored procedureDataSet ds = StoredProcedures.spGetContactDetails("Goldberg",ref CityName, ref StateName);  Console.WriteLine("Display results: " + CityName + " " + StateName);

針對資料庫中的每個預存程序,會產生一個static的方法,放在StoredProcedures類型中。如上代碼所示。

這個方法的源代如下所示,雖然只是個簡單的封裝,卻大大簡化了用戶端調用預存程序的代碼。

public static DataSet spGetContactDetails(  System.String LastName, ref System.String City,   
ref System.String State ){ ArrayList arrayParams = new ArrayList(); SqlParameter paramLastName = new SqlParameter( "@LastName", LastName); paramLastName.SqlDbType = (SqlDbType) Enum.Parse( typeof(SqlDbType), "varchar", true); paramLastName.Direction = ParameterDirection.Input; arrayParams.Add( paramLastName ); SqlParameter paramCity = new SqlParameter( "@City", City); paramCity.SqlDbType = (SqlDbType) Enum.Parse( typeof(SqlDbType), "varchar", true); paramCity.Direction = ParameterDirection.Output; arrayParams.Add( paramCity ); SqlParameter paramState = new SqlParameter( "@State", State); paramState.SqlDbType = (SqlDbType) Enum.Parse( typeof(SqlDbType), "varchar", true); paramState.Direction = ParameterDirection.Output; arrayParams.Add( paramState ); DataSet ds = dm.ExecuteProcedure("spGetContactDetails", (SqlParameter[]) arrayParams.ToArray(typeof(SqlParameter))); City = (System.String) paramCity.Value; State = (System.String) paramState.Value; return ds;}

再舉例,返回資料集的預存程序,下面的預存程序返回城市和居住在城市裡的學生的合計數

CREATE PROC spStudentsByCityAS  SELECT City, Count(c.Id) as 'Total'  FROM Student s, Contact c  WHERE s.FKContactId=c.IDGROUP BY City

C#.NET調用代碼如下所示

DataSet ds1 = StoredProcedures.spStudentsByCity();foreach (DataRow dr in ds1.Tables[0].Rows)       Console.WriteLine ("City: " + dr["City"] + " Total: " + dr["Total"]);

如果預存程序返回多個資料集,如下的代碼所示

ALTER Proc spStudentContact  @LastName varchar(50)ASDECLARE @ContactId intDECLARE @FKContactId intSELECT * FROM Student WHERE LastName=@LastNameSELECT @FKContactId=FKContactID FROM Student WHERE LastName=@LastNameSELECT * FROM Contact WHERE ID=@FKContactId

ORM.NET提供了額外的方法PopulateObjectsFromDataSet來展開得到的資料

DataSet ds = StoredProcedures.spStudentContact("Johnson");  // call the stored procedureString[] arrTables = {"Student","Contact"};   // create the array with the tables included in the DataSetdm.PopulateObjectsFromDataSet(ds,arrTables);StudentCollection students = dm.GetStudentCollectionFromDataSet(); ContactCollection contacts = dm.GetContactCollectionFromDataSet();// Work with the objectsforeach(Contact c1 in contacts)Console.WriteLine("Address: " + c1.Address1);

從代碼可以看出,方法PopulateObjectsFromDataSet把查詢到的資料集填充到指定的collection中。

 

子類化,增加自訂代碼 Sub-classing and extending Generated Class files

ORM.NET考慮到了應用程式開發中,會修改它產生的類型定義。請看代碼

using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;namespace SampleAppBiz{       /// <summary>       /// Wraps a row and it's columns/children/parents       /// This class should be customized.      /// </summary>       public class Student : StudentTemplate       {              /// <summary>              /// Constructor must have a row and data context.              /// </summary>          internal Student( DataManager dataContext, DataRow ROW) : base( dataContext, ROW)          {                     row = ROW;          }       }}

在產生的項目代碼中,添加方法

public string FullName(){    return (this.FirstName + " " + this.LastName);} 

更合適的,應該是添加為屬性

public override string LastName           {                 get                 {                       return (base.LastName.ToLower());                 }                 set                 {                       // ensure that the LastName is always set to                        // lower-case                       base.LastName = value.ToLower();                 }    }

如果資料庫指令碼或是關係發生變化,需要重新代碼實體定義,這些代碼也不會丟失。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.