lambda表达式自学笔记2

本文介绍DataContext在.NET中的使用方法,包括如何生成SQL、执行查询及更新操作,并通过具体代码示例展示了如何利用DataContext与数据库进行交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/wavaya/archive/2011/06/27/2091278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值