使用 AdventureWorks 对象模型 (EDM)

下面示例中 AdventureWorks 客户端应用程序使用的代码将演示 实体数据模型 (EDM) 的几个功能。之前的 AdventureWorks 模型主题中描述的架构是本节代码使用的实体和关联的基础。

架构中设计并映射到存储的类型将生成为可编程对象模型。此模型上的数据可使用公共语言运行库 (CLR) 语法(无需凭借以字符串形式嵌入代码的 SQL 查询)编程。

应用程序配置

使用该对象模型需要连接到存储应用程序数据的数据库。还需要指向由架构生成的 DLL 提供的运行时对象的实体连接。

exe.config 文件中包含用于连接到 SQL Server 数据库并建立实体连接的连接字符串。实体连接就位后,即可从代码访问对象模型中的实体和关联。

开发人员必须将连接字符串文本添加到 exe.config 文件。

providerName="System.Data.EntityClient" 赋值将指定使用架构和架构中定义的映射的实体连接,这将在本节的其他主题中介绍。

<?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>
Note注意

该连接字符串将多个活动结果集设置为 True,为了使每次在同一个连接上打开另一个数据读取器时都在关联上调用 Load 方法,必须进行这样的设置。

使用 AdventureWorks 实体和关联

以下代码演示的查询基于此 AdventureWorks 小节其他主题中的架构中定义的实体和关联。

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);
            }

        }

        
    }
}

另请参见

概念

扩展属性 (CSDL)

其他资源

EDM 规范
架构和映射规范(实体框架)
示例应用程序(实体框架)