Criando um aplicativo do Entity Framework (SQL Server Compact)

Este tópico fornece instruções passo a passo sobre como criar aplicativos do Entity Framework que usam o banco de dados do SQL Server Compact como fonte de dados.

Para criar um novo aplicativo do Entity Framework

  1. No Visual Studio, no menu Arquivo, aponte para Novo e selecione Projeto.

  2. Na lista Tipos de Projeto da caixa de diálogo Novo Projeto, expanda a linguagem de programação que será usada e selecione Visual C# ou Visual Basic.

  3. Na lista Modelos, selecione Aplicativo do Console.

  4. Forneça um nome (como SQLCompactEDMProject) e um local para seu projeto e clique em OK.

  5. Para gerar o EDM (Modelo de Dados de Entidade) para o arquivo Northwind.sdf, copie o arquivo da pasta %Arquivos de Programas%\Microsoft SQL Server Compact Edition\v3.5\Samples para a pasta que contém seu projeto.

  6. No menu Projeto, clique em Adicionar novo item.

  7. No painel Modelos, selecione Modelo de Dados de Entidade ADO.NET.

  8. Digite Northwind.edmx para o nome do modelo e clique em Adicionar.

  9. A primeira página do assistente Entity Data Model Wizard será exibida.

  10. Na caixa de diálogo Choose Model Contents, selecione Generate from database. Clique em Next.

  11. Clique no botão New Connection.

  12. Na caixa de diálogo Connection Properties, clique no botão Change em Data Source. Selecione Microsoft SQL Server Compact 3.5, procure Northwind.sdf e clique em OK.

    A caixa de diálogo Choose Your Data Connection será atualizada com as configurações de conexão do banco de dados.

  13. Confira se a caixa de seleção Save entity connection settings in App.Config as: está marcada e se o valor está definido como NorthwindEntities. Clique em Next.

  14. Na caixa de diálogo Choose Your Database Objects, limpe todos os objetos, expanda Tables e selecione Customers como um objeto de tabela.

  15. Digite NorthwindModel para o Model Namespace.

  16. Clique em Finish para concluir o assistente.

  17. O assistente executa estas ações:

    1. Adiciona referências aos assemblies System.Data.Entity.dll, System.Runtime.Serialization.dll e System.Security.dll.

    2. Gera o arquivo Northwind.edmx que define o EDM.

    3. Cria o arquivo do código-fonte que contém as classes geradas com base no EDM. Você pode exibir o arquivo do código-fonte expandindo o arquivo .edmx no Gerenciador de Soluções.

    4. Cria um arquivo App.Config.

  18. Clique duas vezes no arquivo de configuração de aplicativo do projeto (app.config) e verifique se provider=System.Data.SqlServerCe.3.5 na cadeia de conexão.

  19. Na página de código do aplicativo, adicione os termos a seguir usando instruções:

    C#:

    using NorthwindModel;
    

    Visual Basic:

    Imports SQLCompactEDM.NorthwindModel
    

    Observe que o nome do modelo corresponde ao valor do namespace especificado no arquivo Northwind.edmx.

  20. Copie o exemplo de código a seguir para o arquivo de código. Compile e execute.

Importante

O assembly System.Data.Entity.dll faz parte do SP1 do .NET Framework versão 3.5. Os tópicos de referência gerenciada do assembly System.Data.Entity estão disponíveis na documentação do Entity Framework.

Exemplo

O exemplo de código a seguir fornece três consultas do Entity Framework simples com base no banco de dados de Northwind.sdf do SQL Server Compact:

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

Consulte também

Outros recursos

Entity Framework (SQL Server Compact)