• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
光脚丫思考的专栏
十年窗下无人问,一举成名天下知!
博客园    首页    新随笔    联系   管理    订阅  订阅

光脚丫学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(); 
posted @ 2010-10-30 12:11  光脚丫思考  阅读(381)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3