網頁

Thursday, July 28, 2011

[EF4] Entity Framework Insert / Select Top / Where In

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

使用的版本為ADO.NET Entity Framework 4.1 - Update 1,測試的相關資料請看這篇

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

Insert
public static void EntityInsert(string name, int score)
        {
            tbl_Speed_Test_EF st = new tbl_Speed_Test_EF();
            st.name = name;
            st.score = score;

            using (Died_TestEntities context = new Died_TestEntities())
            {
                try
                {
                    context.tbl_Speed_Test.AddObject(st);
                    context.SaveChanges();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
相當於SQL Command的
insert into [Died_Test].[dbo].[tbl_Speed_Test] (name,score) values(@name,@score)
Entity Framework對於有預設值的欄位也需要手動對edmx改點設定,詳情可以見這篇"Linq to SQL, Entity Framework, SubSonic 3.0 對於預設欄位的處理方式"。



Select Top
public static void EntitySelectTop(int score)
        {
            using (Died_TestEntities context = new Died_TestEntities())
            {
                try
                {
                    tbl_Speed_Test_EF st = context.tbl_Speed_Test.First(p => p.score == score);
                    Console.WriteLine(st.guid + "\t" + st.name + "\t" + st.score);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
相當於SQL Command的
select top 1 * from [Died_Test].[dbo].[tbl_Speed_Test] where [score]=@score



Where In
public static void EntitySelectIn(int[] score)
        {
            using (Died_TestEntities context = new Died_TestEntities())
            {
                try
                {
                    var result = context.tbl_Speed_Test.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);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
相當於SQL Command的
select * from [Died_Test].[dbo].[tbl_Speed_Test] where [score] in (@score1,@score2,@score3.....) order by [score]

No comments:

Post a Comment