Share via


Verwendung des AdventureWorks-Objektmodells (EDM)

Im Code der im folgenden Beispiel gezeigten AdventureWorks-Clientanwendung werden verschiedene Features des Entitätsdatenmodell (EDM) dargestellt. Die in vorherigen Themen zum AdventureWorks-Modell beschriebenen Schemas bilden die Grundlage der vom Code dieses Abschnitts verwendeten Entitäten und Zuordnungen.

Typen, die in Schemas entworfen und Speicher zugeordnet wurden, sind als programmierbare Objektmodelle erstellt. Die Daten dieses Modells sind mit der Common Language Runtime (CLR)-Syntax programmierbar, ohne SQL-Abfragen als Zeichenfolgen in den Code einbetten zu müssen.

Anwendungskonfiguration

Für das Objektmodell ist eine Verbindung zu der Datenbank erforderlich, in der die Anwendungsdaten gespeichert werden. Zudem ist eine Entitätsverbindung zu den Laufzeitobjekten erforderlich, die von der mit den Schemas erstellten DLL bereitgestellt wird.

Die Datei exe.config enthält eine Verbindungszeichenfolge, die verwendet wird, um eine Verbindung zu einer SQL Server-Datenbank sowie eine Entitätsverbindung herzustellen. Wenn eine Entitätsverbindung besteht, kann auf die Entitäten und Zuordnungen im Objektmodell vom Code aus zugegriffen werden.

Der Entwickler muss der Datei exe.config den Verbindungszeichenfolgentext hinzufügen.

Die Zuweisung providerName="System.Data.EntityClient" gibt eine Entitätsverbindung an, die die Schemas und Mappings verwendet, die in anderen Themen dieses Abschnitts gezeigten Schemas definiert wurden.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="AdventureworksContext" connectionString='Metadata=.;
            Provider=System.Data.SqlClient;
            Provider Connection String="server=.\sqlExpress;
            database=Adventureworks;
            Integrated Security=true;Connection Timeout=5;
            multipleactiveresultsets=true"'
            providerName="System.Data.EntityClient"/>
    </connectionStrings>
</configuration>
NoteHinweis

Diese Verbindungszeichenfolge legt "Multiple Active Result Sets" auf true fest. Dies ist erforderlich, um die Load-Methode für Zuordnungen aufzurufen, wenn für dieselbe Verbindung bereits ein weiterer Datenleser geöffnet wurde.

Verwendung von AdventureWorks-Entitäten und -Zuordnungen

Im folgenden Code werden Abfragen dargestellt, die auf Entitäten und Zuordnungen beruhen, die in Schemas in anderen Themen dieses AdventureWorks-Abschnitts definiert werden.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdventureWorks;
using System.Data.Objects;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Collections.ObjectModel;


namespace AdventureworksClient
{
    class Program
    {
        static void Main(string[] args)
        {
            using (AdventureWorksContext objCtx = new AdventureWorksContext())
            {
                // find first 50 employees and display data.
                foreach (Employee employee in
                    objCtx.Employee.Where("it.EmployeeID < 50"))
                {
                    Console.WriteLine("EmployeeID: {0}",
                                              employee.EmployeeID);

                    // Find employee job candidate and print resume.
                    employee.JobCandidate.Load();
                    foreach (JobCandidate jc in employee.JobCandidate)
                        Console.WriteLine("\tJobCandidate: {0} \n\t{1}",
                            jc.JobCandidateID, jc.Resume);


                    // Find manager of employee and display.
                    if (null != employee.Employee2)
                    {
                        employee.Employee2.Employee2Reference.Load();
                        Console.WriteLine("Employee: {0} Manager: {1}",
                             employee.EmployeeID.ToString(),
                             employee.Employee2.EmployeeID.ToString());
                    }

                }

                // Employees IDs 1 - 290. 
                // Find first 50 with contact information.
                foreach (Contact contact in
                     objCtx.Contact.Where("it.ContactID < 50"))
                {
                    Console.WriteLine("Contact: {0} {1} {2}",
                        contact.ContactID, contact.FirstName,
                        contact.LastName);

                    foreach (EmployeeAddress emplAddress in
                                          objCtx.EmployeeAddress)
                    {
                        if (emplAddress.EmployeeID.Equals(contact.ContactID))
                        {
                            ObjectParameter param = new
                            ObjectParameter("p",
                                emplAddress.AddressID);
                            Address address =
                                objCtx.Address.Where(
                               "it.AddressID = @p",
                                param).First();

                            Console.WriteLine(
                              "\tEmployee address: {0}\n\t{1}\n\t{2}",
                              address.AddressLine1,
                              address.City, address.PostalCode);
                        }
                    }
                }

                // Find and display vendors.
                foreach (Vendor vendor in objCtx.Vendor)
                    Console.WriteLine("Vendor: {0}", vendor.Name);

                // Find and display store information.
                foreach (Store store in objCtx.Store)
                    Console.WriteLine("Store: {0}", store.Name);


                // Find and display product information.
                foreach (Product product in objCtx.Product)
                {
                    Console.WriteLine("Product Name: {0}", product.Name);
                    product.ProductModelReference.Load();
                    if (null != product.ProductModel)
                    {
                        Console.WriteLine("Model: {0}",
                            product.ProductModel.ProductModelID.ToString());
                    }
                }
            }

            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=AdventureWorksContext"))
                {
                    // Open the connection.
                    connection.Open();

                    // Access the metadata workspace.
                    MetadataWorkspace workspace =
                       connection.GetMetadataWorkspace();

                    // To run DisplayProperties(workspace, DataSpace.CSpace);
                    // to display the extended properties in the conceptual model.
                    // see Extended Property (CSDL) (link under See Also).
                }
            }
            catch (System.Data.MetadataException exceptionMetadata)
            {
                Console.WriteLine("MetadataException: {0}",
                                exceptionMetadata.Message);
            }
            catch (System.Data.MappingException exceptionMapping)
            {
                Console.WriteLine("MappingException: {0}",
                                 exceptionMapping.Message);
            }

        }

        
    }
}

Siehe auch

Konzepte

Erweiterte Eigenschaft (CSDL)

Weitere Ressourcen

EDM-Spezifikationen
Schemas und Mappingspezifikation (Entity Framework)
Beispielanwendungen (Entity Framework)