lambda表达式自学笔记2
DataContext
DataContext类型(数据上下文)功能:
1.以日志形式记录DataContext生成的SQL
2.执行SQL(包括查询和更新语句)
3.创建和删除数据库
DataContext是实体和数据库之间的桥梁。
定义实体类
Customer.cs
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq.Mapping;
namespace DannyWeb
{
[Table(Name="Customers")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public string CustomerID { get; set; }
[Column(Name = "ContactName")]
public string Name { get; set; }
[Column]
public string City { get; set; }
}
}
[/code]
Default.aspx
[code]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
[/code]
Default.aspx.cs
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;
using DannyWeb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataContext ctx = new DataContext("server=.;database=Northwind;uid=sa;pwd=");
Table<Customer> Customers = ctx.GetTable<Customer>();
GridView1.DataSource = from c in Customers
where c.CustomerID.StartsWith("A")
select new { 顾客ID = c.CustomerID, 顾客名 = c.Name, 城市 = c.City };
GridView1.DataBind();
}
}
[/code]
显示结果:
注意:
要手动添加System.Data.Linq.Mapping引用。
还可以直接使用如下:
[code]
using System.Data.SqlClient;
...
IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx");
DataContext ctx = new DataContext(conn);
...
[/code]
2011-6-2 11:27 danny