Condividi tramite


Creazione di un'applicazione Entity Framework (SQL Server Compact)

In questo argomento vengono fornite istruzioni dettagliate sulla creazione di applicazioni Entity Framework che utilizzano il database di SQL Server Compact come origine dati.

Per creare una nuova applicazione Entity Framework

  1. In Visual Studio scegliere Nuovo dal menu File, quindi selezionare Progetto.

  2. Nell'elenco Tipi progetto della finestra di dialogo Nuovo progetto espandere il linguaggio di programmazione da utilizzare, quindi selezionare Visual C# o Visual Basic.

  3. Nell'elenco Modelli selezionare Applicazione console.

  4. Specificare un nome, ad esempio SQLCompactEDMProject, e un percorso per il progetto, quindi fare clic su OK.

  5. Per generare il modello EDM per Northwind.sdf, copiare il file Northwind.sdf dalla cartella %Programmi%\Microsoft SQL Server Compact Edition\v3.5\Samples nella cartella del progetto.

  6. Scegliere Aggiungi nuovo elemento dal menu Progetto.

  7. Nel riquadro Modelli selezionare ADO.NET Entity Data Model.

  8. Digitare Northwind.edmx come nome del modello, quindi fare clic su Aggiungi.

  9. Verrà visualizzata la prima pagina della Procedura guidata Entity Data Model.

  10. Nella finestra di dialogo Scegli contenuto Model selezionare Genera da database, quindi fare clic su Avanti.

  11. Fare clic sul pulsante Nuova connessione.

  12. Nella finestra di dialogo Proprietà connessione fare clic sul pulsante Cambia in Origine dati. Selezionare Microsoft SQL Server Compact 3.5, passare a Northwind.sdf, quindi fare clic su OK.

    La finestra di dialogo Scegliere la connessione dati verrà aggiornata con le impostazioni di connessione al database.

  13. Verificare che la casella di controllo Salva impostazioni stringa di connessione entity in App.Config come: sia selezionata e che il valore sia impostato su NorthwindEntities, quindi fare clic su Avanti.

  14. Nella finestra di dialogo Scegli oggetti di database cancellare tutti gli oggetti, espandere Tabelle, quindi selezionare Customers come oggetto tabella.

  15. Digitare NorthwindModel per Spazio dei nomi Model.

  16. Fare clic su Fine per completare la procedura guidata.

  17. La procedura guidata consente di effettuare le operazioni seguenti:

    1. Aggiunta di riferimenti agli assembly System.Data.Entity.dll, System.Runtime.Serialization.dll e System.Security.dll.
    2. Generazione del file Northwind.edmx che definisce il modello EDM.
    3. Creazione di un file del codice sorgente che contiene le classi generate in base al modello EDM. È possibile visualizzare il file del codice sorgente espandendo il file .edmx in Esplora soluzioni.
    4. Creazione di un file App.Config.
  18. Fare doppio clic sul file di configurazione dell'applicazione del progetto (app.config) e verificare l'impostazione provider=System.Data.SqlServerCe.3.5 nella stringa di connessione.

  19. Nella tabella codici per l'applicazione aggiungere le istruzioni USING seguenti:

    C#:

    using NorthwindModel;
    

    Visual Basic:

    Imports SQLCompactEDM.NorthwindModel
    

    Si noti che il nome del modello corrisponde al valore dello spazio dei nomi specificato nel file Northwind.edmx.

  20. Copiare l'esempio di codice seguente nel file di codice, quindi compilarlo ed eseguirlo.

Importante

L'assembly System.Data.Entity.dll fa parte della versione SP1 di .NET Framework 3.5. Nella documentazione di Entity Framework sono disponibili argomenti relativi al riferimento gestito per l'assembly System.Data.Entity.

Esempio

Nell'esempio di codice seguente vengono eseguite tre semplici query Entity Framework sul database Northwind.sdf di 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

Vedere anche

Concetti

Entity Framework (SQL Server Compact)

Guida e informazioni

Assistenza (SQL Server Compact 3.5 Service Pack 1)