Создание приложения платформы Entity Framework (SQL Server Compact)

В этом разделе приводятся пошаговые инструкции по созданию приложений на платформе Entity Framework, использующих в качестве источника данных базу данных SQL Server Compact.

Создание нового приложения на платформе Entity Framework

  1. В среде Visual Studio укажите в меню Файл команду Создать, а затем выберите команду Проект.

  2. В списке Типы проектов диалогового окна Новый проект разверните узел языка программирования, который будет использоваться, и выберите Visual C# или Visual Basic.

  3. В списке Шаблоны выберите пункт Приложение командной строки.

  4. Укажите имя (например, SQLCompactEDMProject) и расположение проекта, затем нажмите кнопку ОК.

  5. Для создания модели EDM на основе файла Northwind.sdf скопируйте файл Northwind.sdf из папки «%ProgramFiles%\Microsoft SQL Server Compact Edition\v3.5\Samples» в папку, в которой находится проект.

  6. В меню Проект выберите Добавить новый элемент.

  7. В области Шаблоны выберите пункт Модель EDM ADO.NET.

  8. В качестве имени модели введите Northwind.edmx и нажмите кнопку Добавить.

  9. Откроется первая страница мастера моделей EDM.

  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. Создает файл Northwind.edmx, в котором определена модель EDM.
    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 является частью пакета обновления 1 (SP1) версии .NET Framework 3.5. Разделы справочника по написанию управляемого кода, касающиеся сборки System.Data.Entity, находятся в документации по платформе Entity Framework.

Пример

Следующий пример кода содержит три простых запроса Entity Framework к базе данных SQL Server Compact Northwind.sdf:

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 с пакетом обновления 1)