共用方式為


How to: Create and Execute Object Queries using an Entity Mapped to Separate Tables

When using legacy data in an Entity Data Model (EDM), it is sometimes useful to be able to map a single entity to two tables in the database. This can be done when two tables share a common key, as is the case with the Customer and Store tables of the AdventureWorks sample database that ships with SQL Server 2005.

The code in the example in this topic uses the EDM defined in the topic How to: Define a Model with Single Entity Mapped to Two Tables. Running object queries against an entity mapped to two tables is identical to querying other entities. The mapping does not affect code syntax.

To create the project using an entity mapped to separate tables

  1. Create a console application.

  2. Add a reference to the EDM defined in How to: Define a Model with Single Entity Mapped to Two Tables.

  3. Add references to System.Data.Entity and System.Runtime.Serialization.

  4. Add the preprocessor directive for the AdventureWorksModel implemented in How to: Define a Model with Single Entity Mapped to Two Tables.

Example

The entity mapped to separate tables in this example can be used to enumerate results in a foreach loop. The following code displays properties from both tables of the Store entity mapping.

Option Explicit On
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports StoreCustomer_VB.AdventureWorksModel

Module Module1
    Sub Main()
        Using objCtx As AdventureWorksEntities =
                        New AdventureWorksEntities()
            For Each store As Store In objCtx.Store
                Console.WriteLine("CustomerId: {0} Name: {1} " & vbNewLine _
                    & vbTab & "Account#: {2} SalespersonId: {3}", _
                    store.CustomerID, store.Name, store.AccountNumber, store.SalesPersonID)
                Console.Write(vbNewLine)
            Next
        End Using
    End Sub
End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdventureWorksModel;

namespace ClientStoreCustomerSplit
{
    class Program
    {
        static void Main(string[] args)
        {
            using (AdventureWorksEntities objCtx = new AdventureWorksEntities())
            {
                foreach (Store store in objCtx.Store)
                    Console.WriteLine("CustomerId: {0} Name: {1} \r\n\t" +
                    "Account#: {2} SalespersonId: {3}",
                        store.CustomerID, store.Name, 
                        store.AccountNumber, store.SalesPersonID );
            }
        }
    }
}

See Also

Tasks

How to: Define a Model with Single Entity Mapped to Two Tables