如何:使用映射到单独表的实体创建和执行对象查询
当在实体数据模型 (EDM) 中使用早期数据时,如果能够将单个实体映射到数据库中的两个表,则有时会很有用。当两个表共享一个公共键(例如,使用随 SQL Server 2005 附带的 AdventureWorks 示例数据库的 Customer 表和 Store 表)时,可以执行此操作。
本主题的示例中的代码使用在主题如何:通过将单个实体映射到两个表以定义模型中定义的 EDM。针对映射到两个表的实体运行对象查询与查询其他实体完全相同。映射不影响代码语法。
使用映射到单独表的实体创建项目
创建控制台应用程序。
添加对在如何:通过将单个实体映射到两个表以定义模型中定义的 EDM 的引用。
添加对 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 );
}
}
}
}