網頁

Thursday, July 28, 2011

[SubSonic] SubSonic 3.0 Insert / Select Top / Where In

同前面LINQEF,這篇也是測試ORM的語法,順便拿來當備忘錄的。

使用的版本為SubSonic 3.0,測試的相關資料請看這篇

下面就是以 SubSonic 去做 Insert / Select Top / Where In 的範例,如果有效率更好的寫法,麻煩請跟我說,感謝。

Insert
public static void SubSonicInsert(string name, int score)
        {
            Data.tbl_Speed_Test st= new Data.tbl_Speed_Test();
            st.name = name;
            st.score = score;
            st.Save();
        }
語法超短的,相當於SQL Command的
insert into [Died_Test].[dbo].[tbl_Speed_Test] (name,score) values(@name,@score)
SubSonic對有預設值的欄位也需要手動對ActiveRecord.cs(如果你是用ActiveRecord)改點設定,詳情可以見這篇"Linq to SQL, Entity Framework, SubSonic 3.0 對於預設欄位的處理方式"。



Select Top
public static void SubSonicSelectTop(int score)
        {
            var result = Data.tbl_Speed_Test.Find(x => x.score == score).Take(1);
            foreach (var item in result)
            {
                Console.WriteLine(item.guid + "\t" + item.name + "\t" + item.score);
            }
        }
相當於SQL Command的
select top 1 * from [Died_Test].[dbo].[tbl_Speed_Test] where [score]=@score



Where In
public static void SubSonicSelectIn(int[] score)
        {
            List<Data.tbl_Speed_Test> result = new Data.Died_TestDB().Select.From<Data.tbl_Speed_Test>()
                .Where(Data.tbl_Speed_TestTable.scoreColumn).In(score).OrderAsc(Data.tbl_Speed_TestTable.scoreColumn).ExecuteTypedList<Data.tbl_Speed_Test>();
            foreach (var item in result)
            {
                Console.WriteLine(item.guid + "\t" + item.name + "\t" + item.score);
            }
        }
相當於SQL Command的
select * from [Died_Test].[dbo].[tbl_Speed_Test] where [score] in (@score1,@score2,@score3.....) order by [score]

No comments:

Post a Comment