Linq 第二天

来源:互联网 发布:red5 fms nginx 编辑:程序博客网 时间:2024/05/29 15:33
大家知道在开发数据时,数据一般是关系型数据,然而数据和对象是什么关系?linq就主要是解决数据不等对象而产生。有了Linq数据和对象之间就可以有一个一一对应的关系了。而且这些是可以根据数据库生成这种影射的代码,也可以根据影射代码生成数据库。就是说,数据库和影射代码实现了相互转化。

    1、先添加Linq to SQL 类,命名为Northwind.dbml,然后再该类添加一数据表Customers

如图:                                                                                                                                                                                                                           

从图的Northwind.designer.cs文件可以看到

  1. [System.Data.Linq.Mapping.DatabaseAttribute(Name="Northwind")]
  2.     public partial class NorthwindDataContext : System.Data.Linq.DataContext
  3.     {
  4.         
  5.            
  6.     [Table(Name="dbo.Customers")]
  7.     public partial class Customers : INotifyPropertyChanging, INotifyPropertyChanged
  8.     {
  9.         
  10.         private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
  11.         
  12.         private string _CustomerID;      

可以看到NorthwindDataContext是必须从DataContext 类继承,这样就获得Linq的支持。

 

2、添加一窗体Form1,然后在窗体添加dataGridView1,后如代码如下:

  1. private void Form1_Load(object sender, EventArgs e)
  2.         {
  3.             NorthwindDataContext db = new NorthwindDataContext();
  4.             var c = from p in db.Customers
  5.                     select p;
  6.             dataGridView1.DataSource = c;
  7.         }

 

运行效果图:

 

原创粉丝点击