您的位置:首页 > 其它

lambda表达式自学笔记2

2011-06-27 13:22 483 查看

DataContext     DataContext类型(数据上下文)功能:
    1.以日志形式记录DataContext生成的SQL
    2.执行SQL(包括查询和更新语句)
    3.创建和删除数据库
DataContext是实体和数据库之间的桥梁。 定义实体类
Customer.cs


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; }     }
}
Default.aspx

<%@ 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>

Default.aspx.cs

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();
    }
}
显示结果:   注意:
要手动添加System.Data.Linq.Mapping引用。 还可以直接使用如下:

using System.Data.SqlClient;
...
IDbConnection conn = new SqlConnection("server=xxx;database=Northwind;uid=xxx;pwd=xxx"); DataContext ctx = new DataContext(conn);
...
2011-6-2 11:27 danny

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: