使用簡介<EntityFramework6.0>

Halower發表於2014-09-09

 

序言

在這一篇中,我們將演示EnitityFramework基本的建模【建模也是EntityFramework最核心的特性】範例,例如實體的分離和繼承等。我們開始了演示如何建立一個簡單的概念模型的例子,然後讓EnitityFramework建立底層資料庫。在餘下的例子中,我們將告訴你如何從現有的表和資料庫關係建立模型。

建立一個簡單的Model

1.點選新增新建項,選擇Data下的ADO.NET實體模型,並選擇空模型。

 2.右鍵選擇新增實體

3.將實體命名為Person,實體集命名為People,新增名為Id,型別為Int32的鍵屬性。

4.新增標量屬性

 

 5.新增標量屬性FirstName. LastName, MiddleName,PhoneNumber,同時指定鍵屬性Id的資料庫生成策略

 6.空白處右鍵-->屬性,修改實體容器名稱為EF6RecipesContext,資料庫架構名稱為article2,這些都是為更好地管理Model做的有意義的動作。

7.右鍵選擇根據模型生成資料庫,選擇建立新的連線,選擇目標資料庫

8.在.edmx檔案中生成倉儲模型,並執行資料庫指令碼

 它是怎麼工作的

using System;

namespace EntityFrameworkDemo
{
    class Program
    {
        static void Main()
        {
            using (var context=new EF6RecipesContext())
            {
                var person = new Person
                {
                    FirstName = "Robert",
                    MiddleName = "Allen",
                    LastName = "Doe",
                    PhoneNumber = "867-5309"
                };
                context.People.Add(person);
                person = new Person
                {
                    FirstName = "John",
                    MiddleName = "K.",
                    LastName = "Smith",
                    PhoneNumber = "824-3031"
                };
                context.People.Add(person);
                person = new Person
                {
                    FirstName = "Billy",
                    MiddleName = "Albert",
                    LastName = "Minor",
                    PhoneNumber = "907-2212"
                };
                context.People.Add(person);
                person = new Person
                {
                    FirstName = "Kathy",
                    MiddleName = "Anne",
                    LastName = "Ryan",
                    PhoneNumber = "722-0038"
                };
                context.People.Add(person);
                context.SaveChanges();
            }
            using (var context=new EF6RecipesContext())
            {
                foreach (var person in context.People)
                {
                    Console.WriteLine("{0} {1} {2}, Phone: {3}",
                            person.FirstName, person.MiddleName,
                            person.LastName, person.PhoneNumber);
                }
            }
            Console.ReadKey();
        }
    }
}

執行效果

 至於使用using的好處,這裡就不多說了,因為這也是最基礎的。下面是書中的解釋片段,不熟悉的同學可以看看

      There are a few nice features of using()statements. First, when the code execution leaves the using() {}block,
the Dispose()method on the context will be called because DbContext implements the IDisposable interface. For
DbContext, the Dispose()method closes any active database connections and properly cleans up any other resources
that need to be released.
     Second, no matter how the code leaves the using(){}block, the Dispose()method is called. Most importantly,
this includes return statements and exceptions that may be thrown within the code block. The using(){}block is kind
of a guarantee that critical resources will be reclaimed properly.
  The best practice here is always to wrap your code in the using(){}block when creating new instances of
DbContext. It’s one more step to help bulletproof your code

 從已存在的資料庫中生成模型

問題

現有一個已存在的資料庫中的表,假設也有一些檢視,已經一些外來鍵約束,你想為這個資料庫建立模型

解決方案

你的資料庫中的結構可能是這樣:

首先我們安裝前面的步驟,開啟向導,選擇由資料庫生成,並選擇需要操作的表和檢視

點選完成後,EntityFramework會推斷出Poet和Poem,以及Meter和Poem之間一對多的關係

從模型瀏覽器中我們可以看出一首詩對應一個作者和一個分類,分別對應Poet和Meter導航屬性,如果我們有一個Poem的實體,那麼導航屬性Poet也會包含一個詩人的實體的集合【因為是一對多的關係】,同理Meter也是如此。因為SQLSERVER不支援在檢視上定義關係,因此vwLiberary上市一組空的導航屬性

它是怎麼工作的

using (var context = new EF6RecipesEntities())
            {
                var poet = new Poet {FirstName = "John", LastName = "Milton"};
                var poem = new Poem {Title = "Paradise Lost"};
                var meter = new Meter {MeterName = "Iambic Pentameter"};
                poem.Meter = meter;
                poem.Poet = poet;
                context.Poems.Add(poem);
                poem = new Poem {Title = "Paradise Regained", Meter = meter, Poet = poet};
                context.Poems.Add(poem);
                poet = new Poet {FirstName = "Lewis", LastName = "Carroll"};
                poem = new Poem {Title = "The Hunting of the Shark"};
                meter = new Meter {MeterName = "Anapestic Tetrameter"};
                poem.Meter = meter;
                poem.Poet = poet;
                context.Poems.Add(poem);
                poet = new Poet {FirstName = "Lord", LastName = "Byron"};
                poem = new Poem {Title = "Don Juan", Meter = meter, Poet = poet};
                context.Poems.Add(poem);
                context.SaveChanges();
            }
            using (var context = new EF6RecipesEntities())
            {
                var poets = context.Poets;
                foreach (var poet in poets)
                {
                    Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName);
                    foreach (var poem in poet.Poems)
                    {
                        Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName);
                    }
                }

            }
             // using our vwLibrary view
            using (var context = new EF6RecipesEntities())
            {
                var items = context.vwLibraries;
                foreach (var item in items)
                {
                    Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
                    Console.WriteLine("\t{0} ({1})", item.Title, item.MeterName);
                }
            }

 

執行效果

我們使用SQLSERVER profile監視這段程式碼的執行情況發現,並不是執行完var poets = context.vwLibraries;就立即去資料庫中抓取資料,而知在執行foreach的時候才去查詢之後將結果存放在記憶體中對資料進行不經過資料庫直接從中讀取,總之當前可以認為它是用到的時候才去執行,詳細的流程待後續學習在進行總結。

 

相關文章