如何:查询映射到不同表的实体
在概念模型中使用旧式数据时,有时可以将一个实体映射到数据库中的两个表会非常有用。 当两个表共享一个公共键(例如,使用随 SQL Server 2005 附带的 AdventureWorks 示例数据库的 Customer 表和 Store 表)时,可以执行此操作。
本主题的示例中的代码使用主题如何:定义单个实体映射到两个表的模型中定义的概念模型。 针对映射到两个表的实体运行对象查询与查询其他实体完全相同。 映射不影响代码语法。
创建一个控制台应用程序。
添加对如何:定义单个实体映射到两个表的模型中定义的概念模型的引用。
添加对 System.Data.Entity 和 System.Runtime.Serialization 的引用。
为在如何:定义单个实体映射到两个表的模型中实现的 AdventureWorksModel 添加预处理器指令。
本示例中映射到单独表的实体可用来枚举 foreach 循环中的结果。 以下代码显示来自存储实体映射的这两个表中的属性。
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 );
}
}
}
}