光脚丫学LINQ(018):创建并使用自定义的数据上下文
视频演示:http://u.115.com/file/f233b821ab
从数据库的强类型化视图着手要容易得多。 通过将 DataContext 对象强类型化,您无需调用 GetTable。 当您使用强类型化的 DataContext 对象时,您可以在所有查询中使用强类型化表。
在以下步骤中,您将创建 Customers 作为映射到数据库中的 Customers 表的强类型化表。
对DataContext对象进行强类型化
public class Northwind : DataContext
{
// Table<T> abstracts database details per table/data type.
public Table<Customer> Customers;
public Table<Order> Orders;
public Northwind(string connection) : base(connection) { }
}
public class Northwind : DataContext
{
// Table<T> abstracts database details per table/data type.
public Table<Customer> Customers;
public Table<Order> Orders;
public Northwind(string connection) : base(connection) { }
}
然后就可以使用下面的方式来使用自定义的强类型数据上下文了,从而代替系统自带的DataContext。
// Use a connection string.
Northwind db = new Northwind(@"C:\linqtest5\Northwind.mdf");
// Query for customers from Seattle.
var SeattleCustomers =
from CustomerObject in db.Customers
where CustomerObject.City == "Seattle"
select CustomerObject;
foreach (var CustomerObject in SeattleCustomers)
{
Console.WriteLine("ID={0}", CustomerObject.CustomerID);
}
// Freeze the console window.
Console.ReadLine();
浙公网安备 33010602011771号