DataContext与实体

 

二、

现在,创建一个ASP.NET页面,然后在页面上加入一个GridView控件,使用下面的代码进行绑定数据:
 
 1 using System.Data.Linq;
 2 public partial class _Default : System.Web.UI.Page
 3 {
 4     protected void Page_Load(object sender, EventArgs e)
 5     {
 6         DataContext cxt = new DataContext("server = .;database = 'NorthWind' ;Integrated Security = true");
 7         Table<Customer> cuts = cxt.GetTable<Customer>();
 8         GridView1.DataSource = from c in cuts
 9                                where c.City.Length  > 3 
10                                select new { 顾客ID = c.CustomerID, 顾客Name = c.Name,顾客City = c.City};
11 
12         GridView1.DataBind();
13     }
14 }

使用DataContext类型把实体类和数据库中的数据进行关联。你可以直接在DataContext的构造方法中定义连接字符串,也可以使用IDbConnection:

 

using System.Data.SqlClient;

IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx");

DataContext ctx = new DataContext(conn);

 

之后,通过GetTable获取表示底层数据表的Table类型,显然,数据库中的Customers表的实体是Customer类型。随后的查询句法,即使你不懂SQL应该也能看明白。从Customers表中找出CustomerID以“A”开头的记录,并把CustomersID、Name以及City封装成新的匿名类型进行返回。

 

一、 

DataContext类型(数据上下文)是System.Data.Linq命名空间下的重要类型,用于把查询句法翻译成SQL语句,以及把数据从数据库返回给调用方和把实体的修改写入数据库。
    DataContext提供了以下一些使用的功能:
        以日志形式记录DataContext生成的SQL
       执行SQL(包括查询和更新语句)
       创建和删除数据库
DataContext是实体和数据库之间的桥梁,那么首先我们需要定义映射到数据表的实体。

 

定义实体类,引入:using System.Data.Linq.Mapping;

 1 [Table(Name="Customers")]
 2 public class Customer
 3 {
 4     public Customer()
 5     {
 6         //
 7         //TODO: 在此处添加构造函数逻辑
 8         //
 9     }
10     [Column(IsPrimaryKey=true)]
11     public int CustomerID { get; set; }
12 
13     [Column(Name="ContactName")]
14     public string Name { get; set; }
15 
16     [Column]
17     public string City { get; set; }
18 
19 }

 以Northwind数据库为例,上述Customer类被映射成一个表,对应数据库中的 Customers表。然后在类型中定义了三个属性,对应表中的三个字段。其中,CustomerID字段是主键,如果没有指定Column特性的Name属性,那么系统会把属性名作为数据表的字段名,也就是说实体类的属性名就需要和数据表中的字段名一致。

 

 

posted @ 2013-07-13 16:52  Big.Eagle  阅读(3107)  评论(0编辑  收藏  举报