SubSonic3.0使用例子


  前段時間開發的框架使用了SubSonic2.2以后,覺得開發效率提高了不少,后期維護起來也非常方便,不由的喜歡上了SubSonic。中間有想過升級到更高版本,但度娘一下就放棄了,只有極少的中文版說明,而且中文版說明大多也是從英文版的DOC文檔里翻譯過來,沒有更詳細更細致的說明。使用SubSonic2.2一段時間后,覺得SubSonic插件雖然技術很成熟,但有一些調用起來不是很靈活,比較繁瑣,所以一直想了解3.0,看看有沒有更好更新的改進。SubSonic有很多人在用,使用SubSonic2.2版本以下的人也很多,但3.0以后就好像少了,有時想查找3.0的相關中文資料,找來找去就那幾篇,對於更詳細的說明介紹就很少,逼得沒辦法,只能自己來研究了。這段時間公司有新的項目,所以一開始就想稱這個機會,學習一下3.0並應用到項目當中。前幾天弄好開發的相關文檔與數據字典后,就開始學習3.0,前后經歷了兩天多非常痛苦的日子(不停的使用度娘,最后找不到相關文檔以后,只能進入官網查看E文說明,然后查看插件源碼,了解相關的調用),終於搞定了3.0並將框架搭建了起來。然后趕快編寫了本使用說明例子,給同事熟悉。

     SubSonic3.0給我最大的感受就是比2.2版本大大的減負了,更加個性化。去掉了很多重復的功能,增加了Linq的應用,數據庫生成模版可以根據自己的需要隨意修改......不過也存在不少小問題,比如有一些必要屬性沒有了(例如使用Select或SqlQueue查詢時需要使用Distinct,怎么找不找不到,使用db.表名.Select().Distinct()才有).....對於這些問題,如果不自己修改源碼的添加相關功能的話,那只能使用硬編碼,直接使用SQL語句了.....當然也有可能是我自己還沒有找到調用方法

     例子中有一些代碼未經過調試(由於是一口氣寫出來,沒有執行過),可能運行時會存在問題,敬請諒解,有的調用函數是我自己修改官方源碼添加了,官方的Dll里並不包含此功能,所以會存在無法編譯的現象,請將那段代碼注釋掉就可以了。發表本編內容,只要主為了和大家共同學習共同進步,有興趣的朋友可以加加Q群(327360708)或Email給我(1654937#qq.com),大家一起探討,由於本人工作很繁忙,如果疑問請先留言,回復不及時也請諒解。

     下面是SubSonic3.0常用的調用例子

public void test()
 {

            //獲取數據源——主要用於綁定連接的服務器,如果有多台服務器多個數據庫時,可使用不同的數據源來進行綁定查找
            var provider = SubSonic.DataProviders.ProviderFactory.GetProvider();
            //定義事務,給后面的事務調用
            var batch = new BatchQuery(provider);


            //-------------------------------------------------------------------------------
            // 實體Model類增刪查改使用方式
            //-------------------------------------------------------------------------------
            //新增
            Information info = new Information();
            info.Title = "標題";
            info.Content = "內容";
            info.Url = "http://www.baidu.com";
            info.AddUserInfoId = 1;
            info.AddUserInfoName = "Empty";
            info.AddDate = DateTime.Now;
            info.Save();
            //info.Add();  //也可以使用這個函數進行添加

            //修改
            info = new Information(x=> x.Id == 1);
            info.Title = "標題";
            info.Content = "內容";
            info.Url = "http://www.baidu.com";
            info.AddUserInfoId = 1;
            info.AddUserInfoName = "Empty";
            info.AddDate = DateTime.Now;
            info.Save();
            //info.Update();  //也可以使用這個函數進行更新

            //刪除
            info.Delete();  //刪除當前記錄,比如使用查詢或修改獲取到的記錄
            Information.Delete(x => x.Id == 1); //刪除主鍵Id為1的記錄
           

            //查詢
            //查詢全部記錄
            IEnumerable<Information> ierr = Information.All();
            DataTable dt = ConvertFun.ConvertToDataTable(ierr);

            //查詢指定條件的記錄
            IList<Information> il = Information.Find(x => x.Id == 1);
            dt = ConvertFun.IListToDataTable(il);

            //使用Id倒序排序,獲取第一頁記錄(每頁10條記錄)
            il = Information.GetPaged("Id Desc", 1, 10);
            //il = Information.GetPaged(1, 10);  //還可以不加排序

            //獲取主鍵列名
            string keyColumn = Information.GetKeyColumn();

            //判斷主鍵Id為1的記錄是否存在
            bool isExists = Information.Exists(x => x.Id == 1);

            //獲取符合條件的第一條記錄實體
            info = Information.SingleOrDefault(x => x.Id == 1);

 

            //-------------------------------------------------------------------------------

 

            //-------------------------------------------------------------------------------
            // 查詢類的使用方式
            //-------------------------------------------------------------------------------

            //Select,是SqlQuery的子類,將Select直接換成SqlQuery也可以,兩者只有個另屬性與方法不同
            Select select = new Select();
            //只顯示指定的列
            //Select select = new Select(new string[] { InformationTable.IdColumn, InformationTable.TitleColumn });

            select.From<Information>();
           
            //添加查詢條件
            select.Where(InformationTable.IdColumn).IsLessThanOrEqualTo(10).And(InformationTable.TitleColumn).StartsWith("");
            select.Where<Information>(x => x.Title == "標題");
            //查詢時括號添加例子
            //select.Openexpression_r().Where("").IsEqualTo(0).Or("").IsEqualTo(11).Closeexpression_r().And("").IsEqualTo(3);

            //設置去重復——SubSonic沒有去重復選項,需要自己手動修改Dll源碼
            select.Distinct(true);
            ////select.IsDistinct = true;

            //設置查詢數量
            select.Top("10");

            //添加排序
            select.OrderAsc(InformationTable.IdColumn);
            select.OrderDesc(InformationTable.TitleColumn);
            ////List<string> orderbyList = new List<string>();
            //orderbyList.Add(InformationTable.IdColumn + " Asc");
            //orderbyList.Add(InformationTable.TitleColumn + " Desc");
            //select.OrderBys = orderbyList;

            //設為刪除語句,默認為QueryType.Select
            //select.QueryCommandType = QueryType.Delete;
            //select.Execute();

            //設置分頁,獲取第一頁記錄(每頁10條記錄)
            select.Paged(1, 10);


            //獲取查詢語句
            string sql = select.SQLCommand;


            //執行查詢
            dt = select.ExecuteDataTable();
            //int n = select.Execute();
            //IDataReader idr = select.ExecuteReader();
            //object obj = select.ExecuteScalar();
            //info = select.ExecuteScalar<Information>();
            //info = select.ExecuteSingle<Information>();
            //List<Information> lif = select.ExecuteTypedList<Information>();
            //List<Information> lif = select.ToList<Information>();


            //查詢總記錄數
            select.GetRecordCount();


            //-------------------------------------------------------------------------------

 


            //-------------------------------------------------------------------------------
            // 三種為SqlQuery添加條件的方式
            //-------------------------------------------------------------------------------
            //定義
            SqlQuery sqlQuery = new Select().From<InformationTable>();
            //設為刪除語句
            //sq.QueryCommandType = QueryType.Delete;
            //創建條件
            List<ConditionFun.SqlqueryCondition> list = new List<ConditionFun.SqlqueryCondition>();
            list.Add(new ConditionFun.SqlqueryCondition(ConstraintType.And, InformationTable.IdColumn, Comparison.LessOrEquals, 10));

            //添加條件
            //方法一,直接賦值
            sqlQuery.Constraints = ConditionFun.SqlqueryCondition.Condition(list);
            //方法二,使用函數賦值,本方法可以使用在一連串命令一起使用時(即后面還可以繼續使用.來添加其他命令)
            //sq.Where(ConditionFun.SqlqueryCondition.Condition(wheres));
            //方法三,使用自定義函數添加綁定
            //ConditionFun.SqlqueryCondition.AddSqlqueryCondition(sq, wheres);

            //執行語句
            sqlQuery.Execute();
            //-------------------------------------------------------------------------------

 

 

 

            //-------------------------------------------------------------------------------
            // HotelDBDB查詢類的使用方式
            //-------------------------------------------------------------------------------

            HotelDBDB db = new HotelDBDB();
            //平均值
            db.Avg<Information>(x => x.Id);
            //最大值
            db.Max<Information>(x => x.AddDate);
            //最小值
            db.Min<Information>(x => x.AddDate);
            //計算數量
            db.Count<Information>(x => x.AddUserInfoId);


            //其他例子
            IQueryable iqb = db.Information.Select(x => x.Id < 10);
            int count = db.Information.Select(x => x.Id < 10).Distinct().Count();


            //-------------------------------------------------------------------------------
            // HotelDBDB查詢類執行存儲過程方式
            //-------------------------------------------------------------------------------
            //使用db.存儲過程名稱(參數1, 參數2, 參數3);就可以調用存儲過程
            dt = db.P_All_ListPage("表名", "*", 1, 10, 78, "Id Desc", "Id < 1000", "Id", false).ExecuteDataSet().Tables[0];
            //可根據存儲過程返回的數據,調用不同的Execute來獲取

 

 

 

            //-------------------------------------------------------------------------------
            // 直接執行QueryCommand的方式
            //-------------------------------------------------------------------------------
            sql = "select * from Information";
            //執行SQL語句
            //例一
            QueryCommand qcommand = new QueryCommand(sql, provider);
            qcommand.Provider.ExecuteQuery(qcommand);

            //例二
            //創建執行對象
            var q = new SubSonic.Query.QueryCommand(sql, provider);
            q.Provider.ExecuteQuery(q);

            //例三
            batch.QueueForTransaction(qcommand);
            batch.ExecuteTransaction();

            //例四
            provider.ExecuteQuery(qcommand);
            //-------------------------------------------------------------------------------

 


            //-------------------------------------------------------------------------------
            // 使用SimpleRepository查詢方式
            //-------------------------------------------------------------------------------
            //翻頁
            var repo = new SimpleRepository(SimpleRepositoryOptions.RunMigrations);
            //排序和分頁
            var dd = repo.GetPaged<Information>(InformationTable.IdColumn + " desc", 0, 10);
            //添加查詢條件
            dd.Where<Information>(x => x.Id == 1 && x.Title == "標題" && x.Url.StartsWith("度娘"));


            //獲取查詢結果1
            foreach (Information info2 in dd)
            {
                Console.WriteLine(info2.Title);
            }


            //獲取查詢結果2
            List<Information> li = dd.ToList<Information>();


            //-------------------------------------------------------------------------------

 

 

 


            //-------------------------------------------------------------------------------
            // 各種刪除方式
            //-------------------------------------------------------------------------------
            //實體類直接調用刪除
            Information.Delete(x => x.Id == 0);

            //SimpleRepository調用刪除
            var sr = new SimpleRepository(SimpleRepositoryOptions.RunMigrations);
            sr.Delete<Information>(0);

 

            //QueryCommand刪除
            var qd = new SubSonic.Query.QueryCommand("delete from Information where Id = 1", provider);
            qd.Provider.ExecuteQuery(q);


            //SqlQuery刪除
            SqlQuery sq = new Select().From<Information>();
            //設為刪除語句
            sq.QueryCommandType = QueryType.Delete;
            //添加刪除條件
            sq.Where(InformationTable.IdColumn).IsEqualTo(1);
            sq.Execute();

            //-------------------------------------------------------------------------------

 


            //-------------------------------------------------------------------------------
            // 各種查詢方式
            //-------------------------------------------------------------------------------
            //Linq查詢方式
            db = new HotelDBDB();
            var query = new Query<Information>(db.Provider);
            var posts = from p in query
                        where p.Title.StartsWith("M")
                        select p;


           
            query = db.GetQuery<Information>();
            posts = from p in query
                        where p.Title.StartsWith("M")
                        select p;


            //獲取查詢結果1
            foreach (Information info2 in posts)
            {
                Console.WriteLine(info2.Title);
            }

           
            //獲取查詢結果2
            List<Information> li2 = query.ToList<Information>();

 

            //-------------------------------------------------------------------------------
            //Linq多表聯合查詢方法
            var query5 = from r in RoomInfo.All()
                         join rt in RoomType.All() on r.RoomTypeId equals rt.Id
                         where r.RoomNo == "1708" && rt.TypeName == "標准單人房"
                         select r;


            //獲取查詢結果2
            List<Information> li3 = query.ToList<Information>();

 

            var qry = (from c in db.RoomInfos
                       join d in db.RoomTypes on c.RoomTypeId equals d.Id
                       select new RoomListView
                       {
                           RoomNo = c.RoomNo,
                           IsPost = c.IsPost,
                           TypeName = d.TypeName
                       });

            foreach (var view in qry)
            {
                string RoomNo = view.RoomNo;
                byte? IsPost = view.IsPost;
                string TypeName = view.TypeName;
            }


            //-------------------------------------------------------------------------------

 

 


            //-------------------------------------------------------------------------------
            //多個SQL語句需要執行時,可以使用事務
            //例一
            var query1 = new SubSonic.Query.Delete<Information>(InformationTable.IdColumn, 1);
            //var query1 = new SubSonic.Query.Delete<Information>(provider).Where<Information>(x => x.Id == 1).And<Information>(x => x.RoomTypeId == 1);
            batch.QueueForTransaction(query1);

            var query2 = new SubSonic.Query.Delete<Information>(provider).Where<Information>(x => x.Id == 2).Or(InformationTable.IdColumn).IsEqualTo(3);
            batch.QueueForTransaction(query2);
            //execute transaction
            batch.ExecuteTransaction();


            //例二
            batch = null;
            batch = new BatchQuery(provider);

            var query3 = from p in db.Information
                         where
                            p.Id > 1 && p.Id < 10
                         select p;
            batch.Queue(query3);

            var query4 = from p in db.Information
                         where p.Id == 20
                         select p;
            batch.Queue(query4);

            using (var rdr = batch.ExecuteReader())
            {
                if (rdr.Read())
                {
                    //query1 results
                }
                //rdr.MoveNext();
                rdr.NextResult();
                if (rdr.Read())
                {
                    //query2 results
                }
            }

                   //-------------------------------------------------------------------------------

}



//內部類
class RoomListView
    {

        public string RoomNo { get; set; }

        public byte? IsPost { get; set; }

        public string TypeName { get; set; }

    } 

 

  本文章為原創內容,轉載請保留下面信息。

  想了解更多SubSonic3.0的相關問題,請觀注博客:http://www.cnblogs.com/EmptyFS/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM