1 建立实体类的联系
此处使用手动写代码实现。
1.1 Order类
private EntityRef<Customer> _Customer;
public Order()
{
this._Customer = new EntityRef<Customer>();
}
/// <summary>
/// 導航到 Customer
/// </summary>
/// <remarks>
/// 使用 CustomerID 關聯到 Customer ThisKey
/// Order的外鍵(CustomerID) 在 Customer 是主鍵,所以使用 ThisKey
/// </remarks>
[Association(Storage = "_Customer", ThisKey = "CustomerID")]
public Customer Customer
{
get { return this._Customer.Entity; }
set { this._Customer.Entity = value; }
}
注意:定义好实体的联系,就可以使用导航性得到Customer和Order,不需要使用Join。
2 建立客户-订单联系性查询
// Query for customers who have placed orders.
// Any等同于EXISTS
var custQuery2 = Customers
.Where(n => n.Orders.Any()); // EXISTS
foreach (var custObj in custQuery2)
{
//Console.ReadLine();
Console.WriteLine("ID={0}, Qty={1}", custObj.CustomerID,
custObj.Orders.Count);
}
注意:可以不添加联系性,建立一方就可导航了。
3 建立强类型的DataContext对象
/// <summary>
/// 强类型 Northwind 数据库(元数据数据库)
/// </summary>
/// <remarks>
/// 使用强型别 DataContext,不需要调用 GetTable。
/// 数据库可分为:描述数据库和元数据数据库。
/// 此处是使用元数据数据库。
/// </remarks>
public class Northwind : DataContext
{
// 强类型table
public Table<Customer> Customers;
public Table<Order> Orders;
public Northwind(string connection) : base(connection) { }
}
注意:DataContext 的功能
(1)追踪实体的变动
(2)管理缓存
(3)确保多个数据库实体使用同一个类的实例来表示。
(4)代表相关数据库操作的一组逻辑