Thursday, July 28, 2011

[LINQ] LINQ to SQL Insert / Select Top / Where In

之前用幾個ORM去測試速度,想說寫了都寫了,就順便把測試用的語法也貼出來,這樣我健忘時還可以回來找code參考。

測試的相關資料請看這篇

下面就是以LINQ to SQL去做Insert / Select Top / Where In 的範例,我沒有測試過很多種寫法,如果有效率更好的寫法,麻煩請跟我說,感謝。

Insert
public static void LinqInsert(string name, int score)
        {
            LinqModelDataContext DB = new LinqModelDataContext();
            tbl_Speed_Test st = new tbl_Speed_Test();
            st.name = name;
            st.score = score;
            DB.tbl_Speed_Tests.InsertOnSubmit(st);
            try
            {
                DB.SubmitChanges();
            }
            catch(Exception e)
            {
                throw e;
            }
        }
這段語法相當於SQL Command的
insert into [Died_Test].[dbo].[tbl_Speed_Test] (name,score) values(@name,@score)
實際上測試的Table有三個欄位,不過Prime Key的Guid我設成DB自動產生,所以就不塞值進去了,這種方式需要手動對dbml改點設定,詳情可以見這篇"Linq to SQL, Entity Framework, SubSonic 3.0 對於預設欄位的處理方式"。



Select Top
public static void LinqSelectTop(int score)
        {
            LinqModelDataContext DB = new LinqModelDataContext();
            var result = (from p in DB.tbl_Speed_Tests where p.score == score select p).Take(1).ToList();

            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
用LINQ取值時會加上 .ToList() 是因為我在計時的時候,會將foreach那段印出資料的程式mark掉,所以要用.ToList()去避免Dealy Loaded造成計算出來的時間不真實,雖然Dealy Loaded可以去dbml裡關掉,不過還是直接加 .ToList()比較保險。


Where In
public static void LinqSelectIn(int[] score)
        {
            LinqModelDataContext DB = new LinqModelDataContext();

            var result = DB.tbl_Speed_Tests.Where(p => score.Contains<int>((int)p.score)).OrderBy(q => q.score).ToList();

            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]
這邊就可以看出ORM與傳統使用SQL Command的差別,在ORM上要查詢where in一個陣列內的資料,語法相當簡單,但是寫sql command除了定死數量,不然就要去組字串。

No comments:

Post a Comment