共用方式為


建立 Entity Framework 應用程式 (SQL Server Compact)

本主題提供的逐步指示是有關如何建立使用 資料庫當做資料來源的 Entity Framework 應用程式。

建立新的 Entity Framework 應用程式

  1. 在 Visual Studio 的 [檔案] 功能表中,指向 [新增],然後選取 [專案]

  2. [新增專案] 對話方塊的 [專案類型] 清單中,展開您要使用的程式語言,然後選取 Visual C# 或 Visual Basic。

  3. [範本] 清單中,選取 [主控台應用程式]

  4. 提供專案的名稱 (如 SQLCompactEDMProject) 與位置,然後按一下 [確定]

  5. 若要為 Northwind.sdf 產生 Entity Data Model,請從資料夾 %ProgramFiles%\Microsoft SQL Server Compact Edition\v3.5\Samples 將 Northwind.sdf 複製到專案所在的資料夾。

  6. [專案] 功能表上,按一下 [加入新項目]

  7. [範本] 窗格中,選取 [ADO.NET 實體資料模型]

  8. 針對模型名稱輸入 Northwind.edmx,然後按一下 [加入]

  9. 隨即顯示 Entity Data Model 精靈的第一頁。

  10. [選擇模型內容] 對話方塊中,選取 [從資料庫產生]。然後按 [下一步]

  11. 按一下 [新增連接] 按鈕。

  12. [連接屬性] 對話方塊中,按一下 [資料來源] 中的 [變更] 按鈕。選取 [Microsoft SQL Server Compact 3.5],然後瀏覽至 Northwind.sdf,再按一下 [確定]

    [選擇資料連接] 對話方塊會更新為您的資料庫連接設定。

  13. 確定 [將 App.Config 中的實體連接設定儲存為:] 核取方塊已經核取,而且該值設定為 NorthwindEntities。然後按 [下一步]

  14. [選擇您的資料庫物件] 對話方塊中,清除所有物件,並展開 [資料表],然後選取 Customers 當做資料表物件。

  15. 針對 [模型命名空間] 輸入 NorthwindModel

  16. 按一下 [完成] 完成精靈。

  17. 此精靈會執行下列動作:

    1. 加入 System.Data.Entity.dll、System.Runtime.Serialization.dll 和 System.Security.dll 組件的參考。
    2. 產生可定義 EDM 的 Northwind.edmx 檔。
    3. 建立原始程式碼檔,其中包含根據 EDM 所產生的類別。您可以檢視此原始程式碼檔,其方式是在 [方案總管] 中展開此 .edmx 檔。
    4. 建立 App.Config 檔。
  18. 按兩下專案的應用程式組態檔 (app.config),並確定連接字串中有 provider=System.Data.SqlServerCe.3.5

  19. 在應用程式的字碼頁中,使用陳述式加入以下程式碼:

    C#:

    using NorthwindModel;
    

    Visual Basic:

    Imports SQLCompactEDM.NorthwindModel
    

    請注意,此模型的名稱會對應到 Northwind.edmx 檔中指定的命名空間值。

  20. 將下列程式碼範例複製到您的程式碼檔案,然後加以編譯及執行。

重要

System.Data.Entity.dll 組件是 .NET Framework 3.5 版 SP1 的一部分。Entity Framework 文件集中有提供 System.Data.Entity 組件的 Managed 參考主題。

範例

下列程式碼範例會針對 Northwind.sdf 資料庫提供三個簡單的 Entity Framework 查詢:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data;
using NorthwindModel;

namespace SQLCompactEDMProject
{
  class SSC_EntityFrameworkExample
  {
    static void Main(string[] args)
    {
      Console.WriteLine(
        "SQL Server Compact and Northwind Entity Framework Sample:");
      try
      {
        // Establish a connection to the underlying data provider by 
        // using the connection string specified in the config file.
        using (EntityConnection connection = 
             new EntityConnection("Name = NorthwindEntities"))
        {
          // Open the connection.
          connection.Open();

          // A simple query that demonstrates 
          // how to use Entity SQL for entities.
          Console.WriteLine("\nEntity SQL Query:");
          ESQL_Query(connection);

          // A simple query that demonstrates 
          // how to use LINQ to Entities.
          // A new connection is established by using the connection 
          // string in the App.Config file.
          Console.WriteLine("\nLINQ To Entity Query:");
          LINQ_To_Entity_Query();

          // A simple query that demonstrates how to use ObjectContext
          // on data objects with an existing connection.
          Console.WriteLine("\nObject Query:");
          ObjectQuery(connection);

          // Close the connection.
          connection.Close();
       }
     }
     catch (Exception ex)
     {
       Console.WriteLine(ex.Message);
     }
   }

  // A simple query that demonstrates how to use 
  // Entity SQL query for entities.
  private static void ESQL_Query(EntityConnection entityConnection)
  {
    EntityCommand entityCommand = entityConnection.CreateCommand();
    entityCommand.CommandText =
      @"Select Cust.Customer_Id as Id from NorthwindEntities.Customers as Cust order by Cust.Customer_Id";

     EntityDataReader entityDataReader =
     entityCommand.ExecuteReader(CommandBehavior.SequentialAccess);

     while (entityDataReader.Read())
     {
       for (int i = 0; i < entityDataReader.FieldCount; i++)
         Console.Write(entityDataReader[i].ToString() + "\t");
       Console.WriteLine();
     }
  }

  // A simple LINQ query on the Customers entity set in the Northwind 
  // Context.
  // The code example creates a new Northwind Context based on the 
  // settings provided in the App.Config File.
  private static void LINQ_To_Entity_Query()
  {
    using (NorthwindEntities nwEntities = new NorthwindEntities())
    {
      IQueryable<string> customers =
         from c in nwEntities.Customers select c.Company_Name;

      foreach (String c in customers)
      {
        Console.WriteLine(c);
      }
   }
  }

  // The ObjectContext provides access to the collections of data used 
  // by applications. 
  // The following code shows how to open a connection to the 
  // ObjectContext named NorthwindEntities. 
  // With the application configuration file in scope the connection 
  // can be opened with one line of code: 
  // NorthwindEntities nwEntities = new NorthwindEntities(entityConnection).
  private static void ObjectQuery(EntityConnection entityConnection)
  {
     using (NorthwindEntities nwEntities = new 
                  NorthwindEntities(entityConnection))
     {
        foreach (Customers c in nwEntities.Customers)
        {
          Console.WriteLine(c.Company_Name);
        }
      }
  }
  }
}
Imports System.Data.EntityClient
Imports SQLCompactEDM.NorthwindModel

Module Module1
    Sub Main()
        Console.WriteLine("SQL Server Compact and Northwind Entity Framework Sample:")
        Try
            Using connection As EntityConnection = _
                New EntityConnection("Name = NorthwindEntities")
                ' Open the connection.
                connection.Open()

                ' A simple query that demonstrates how to use ESQL for entities.
                Console.WriteLine(vbNewLine & "ESQL Query:")
                ESQL_Query(connection)

                ' A simple query that demonstrates how to use LINQ to Entities.
                ' A new connection is established by using the
                ' connection string in the App.Config file.
                Console.WriteLine(vbNewLine & "LINQ To Entity Query:")
                LINQ_To_Entity_Query()

                ' A simple query that demonstrates how to use ObjectContext
                ' on data objects with an existing connection.
                Console.WriteLine(vbNewLine & "Object Query:")
                ObjectQuery(connection)

                ' Close the connection.
                connection.Close()
            End Using
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

    ' A simple query that demonstrates how to use ESQL for entities.
    Private Sub ESQL_Query(ByVal entityConnection As EntityConnection)
        Dim entityCommand As EntityCommand = entityConnection.CreateCommand
        entityCommand.CommandText = _
            "Select Cust.Customer_Id as Id from NorthwindEntities.Customers as Cust order by Cust.Customer_Id"

        Dim entityDataReader As EntityDataReader = _
            entityCommand.ExecuteReader(CommandBehavior.SequentialAccess)

        Do While entityDataReader.Read
            Dim i As Integer
            For i = 0 To entityDataReader.FieldCount - 1
                Console.Write((entityDataReader.Item(i).ToString & vbTab))
            Next i
            Console.WriteLine()
        Loop
    End Sub

    ' A simple LINQ query on the Customers entity set in the Northwind Context.
    ' The code example creates a new Northwind Context based on the 
    ' settings provided in the App.Config File.
    Private Sub LINQ_To_Entity_Query()
        Using nwEntities As NorthwindEntities = New NorthwindEntities
            Dim customers = From c In nwEntities.Customers Select c.Company_Name

            For Each c In customers
                Console.WriteLine(c)
            Next
        End Using
    End Sub

    ' The ObjectContext provides access to the collections of data used by applications. 
    ' The following code shows how to open a connection to the ObjectContext named NorthwindEntities. 
    ' With the application configuration file in scope the connection can be opened with one line of code: 
    ' NorthwindEntities nwEntities = new NorthwindEntities(entityConnection).
    Private Sub ObjectQuery(ByVal entityConnection As EntityConnection)
        Using nwEntities As NorthwindEntities = New NorthwindEntities(entityConnection)
            Dim c As Customers
            For Each c In nwEntities.Customers
                Console.WriteLine(c.Company_Name)
            Next
        End Using
    End Sub
End Module

另請參閱

概念

Entity Framework (SQL Server Compact)

說明及資訊

取得協助 (SQL Server Compact 3.5 Service Pack 1)