一步一步学Linq to sql(三):增删改

示例数据库

 

字段名

字段类型

允许空

字段说明

ID

uniqueidentifier

 

表主键字段

UserName

varchar(50)

 

留言用户名

PostTime

datetime

 

留言时间

Message

varchar(400)

留言内容

IsReplied

bit

 

留言是否回复

Reply

varchar(400)

留言管理员回复

 

       在数据库中创建一个名为GuestBook的数据库,在里面创建一个tbGuestBook的表,结构如上表。

       创建SQL语句

CREATE TABLE [dbo].[tbGuestBook](
    [ID] [uniqueidentifier] NOT NULL,
    [UserName] [varchar](50) NOT NULL,
    [PostTime] [datetime] NOT NULL,
    [Message] [varchar](500) NULL,
    [IsReplied] [bit] NOT NULL,
    [Reply] [varchar](500) NULL,
 CONSTRAINT [PK_tbGuestBook] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'表主键字段' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'ID' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言用户名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'UserName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言时间' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'PostTime' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言内容' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'Message' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言是否回复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'IsReplied' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'留言管理员回复' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',
@level1name=N'tbGuestBook', @level2type=N'COLUMN',@level2name=N'Reply' GO

 

生成实体类

       右键点击网站项目,选择添加新项,然后选择“Linq to sql Classes”,命名为GuestBook。

   然后打开App_Code里面的GuestBook.dbml。设计视图上的文字提示你可以从服务器资源管理器或者工具箱拖动项到设计界面上来创建实体类。

       那么,我们就在服务器资源管理器中创建一个指向GuestBook数据库的数据连接,然后把tbGuestBook表拖动到GuestBook.dbml的设计视图上,按CTRL+S保存。打开GuestBook.designer.cs可以发现系统自动创建了GuestBook数据库中tbGuestBook表的映射,如下图:

 

简易留言簿

       现在,我们就可以使用Linq to sql完成简易留言簿了。实现以下功能:

l         发表留言(增)

l         查看留言(查)

l         管理员回复留言(改)

l         管理员删除留言(删除)

首先,创建一个Default.aspx,在页面上加入一些控件:

 

<div>

        姓名

        <asp:TextBox ID="tb_UserName" runat="server"></asp:TextBox><br />

        <br />

        留言

        <asp:TextBox ID="tb_Message" runat="server" Height="100px" TextMode="MultiLine" Width="300px"></asp:TextBox><br />

        <br />

        <asp:Button ID="btn_SendMessage" runat="server" Text="发表留言" OnClick="btn_SendMessage_Click" /><br />

        <br />

        <asp:Repeater ID="rpt_Message" runat="server">

        <ItemTemplate>

        <table width="600px" style="border:solid 1px #666666; font-size:10pt; background-color:#f0f0f0">

            <tr>

            <td align="left" width="400px">

            <%# Eval("Message")%>

            </td>

            <td align="right" width="200px">

            <%# Eval("PostTime")%> - <%# Eval("UserName")%>

            </td>

            </tr>

            <tr>

            <td colspan="2" align="right">

            <hr width="300px" />

            管理员回复:<%# Eval("IsReplied").ToString() == "False" ? "暂无" : Eval("Reply")%>

            </td>

            </tr>          

        </table>

        <br/>

        </ItemTemplate>

        </asp:Repeater>

    </div>

 

       你可能很难想象,使用Linq to sql进行数据访问会是这么简单,后台代码:

 

public partial class _Default : System.Web.UI.Page

{

    GuestBookDataContext ctx = new GuestBookDataContext("server=xxx;database=GuestBook;uid=xxx;pwd=xxx");

      

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            SetBind();

        }

    }

    protected void btn_SendMessage_Click(object sender, EventArgs e)

    {

        tbGuestBook gb = new tbGuestBook();

gb.ID = Guid.NewGuid();

        gb.UserName = tb_UserName.Text;

        gb.Message = tb_Message.Text;

        gb.IsReplied = false;

        gb.PostTime = DateTime.Now;

       // ctx.tbGuestBook.Add(gb);

        ctx.tbGuestBook.InsertOnSubmit(gb);//VS2012使用此方法 无Add

        ctx.SubmitChanges();

        SetBind();

    }

    private void SetBind()

    {

        rpt_Message.DataSource = from gb in ctx.tbGuestBook orderby gb.PostTime descending select gb;

        rpt_Message.DataBind();

    }

}

 

前面创建Linq to sql Classes的时候我们输入名字GuestBook,系统就为我们自动创建了GuestBookDataContext(你也可以在GuestBook.Designer.cs中找到类定义)。在绑定的时候我们使用查询句法查询留言表中所有留言,按照发表时间倒序(天哪?这是数据访问吗?好像仅仅定义了一句SQL啊)。在发表留言按钮中,我们为一个tbGuestBook赋值,然后把它加入留言表,再提交更改,就这样完成了记录的插入。

 

       运行效果如下图:

 

       然后,再创建一个Admin.aspx,前台代码如下:

 

<div>

        <asp:Repeater ID="rpt_Message" runat="server" OnItemCommand="rpt_Message_ItemCommand">

        <ItemTemplate>

        <table width="600px" style="border:solid 1px #666666; font-size:10pt; background-color:#f0f0f0">

            <tr>

            <td align="left" width="400px">

            <%# Eval("Message")%>

            </td>

            <td align="right" width="200px">

            <%# Eval("PostTime")%> - <%# Eval("UserName")%>

            </td>

            </tr>

            <tr>

            <td colspan="2" align="right">

            <hr width="300px" />

            <asp:Button ID="btn_DeleteMessage" runat="server" Text="删除留言" CommandName="DeleteMessage" CommandArgument='<%# Eval("ID")%>'/>

            管理员回复:<asp:TextBox runat="server" ID="tb_Reply" TextMode="MultiLine" Width="300px" Text='<%# Eval("Reply")%>'/>

            <asp:Button ID="btn_SendReply" runat="server" Text="发表回复" CommandName="SendReply" CommandArgument='<%# Eval("ID")%>'/>

            </td>

            </tr>          

        </table>

        <br/>

        </ItemTemplate>

        </asp:Repeater>

    </div>

 

       后台代码:

 

 

public partial class Admin : System.Web.UI.Page

{

    GuestBookDataContext ctx = new GuestBookDataContext("server=xxx;database=GuestBook;uid=xxx;pwd=xxx");

       

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            SetBind();

        }

    }

 

    private void SetBind()

    {

        rpt_Message.DataSource = from gb in ctx.tbGuestBooks orderby gb.PostTime descending select gb;

        rpt_Message.DataBind();

    }

    protected void rpt_Message_ItemCommand(object source, RepeaterCommandEventArgs e)

    {

        if (e.CommandName == "DeleteMessage")

        {

            StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);

            ctx.Log = sw;

            tbGuestBook gb = ctx.tbGuestBook.Single(b => b.ID == new Guid(e.CommandArgument.ToString()));

           // ctx.tbGuestBook.Remove(gb); 2012不存在

            ctx.tbGuestBook.DeleteOnSubmit(gb);//2012使用

            ctx.SubmitChanges();

            SetBind();

            sw.Close();

        }

        if (e.CommandName == "SendReply")

        {

            StreamWriter sw = new StreamWriter(Server.MapPath("log.txt"), true);

            ctx.Log = sw;

            tbGuestBook gb = ctx.tbGuestBook.Single(b => b.ID == new Guid(e.CommandArgument.ToString()));

            gb.Reply = ((TextBox)e.Item.FindControl("tb_Reply")).Text;

            gb.IsReplied = true;

            ctx.SubmitChanges();

            SetBind();

            sw.Close();

        }

    }

}

 

运行效果如下图:

 

 

在这里,我们通过Single方法获取一条记录,也就是一个tbGuestBook实例,更新了一些属性后保存也就完成了改这个操作。删除操作更简单,只需要从表中移除对象。你是不是觉得好像不是在操作数据库,像在操作内存中的对象。

       由于写了日志,看看改和删操作会是怎么样的SQL?

 

UPDATE [dbo].[tbGuestBook]

SET [IsReplied] = @p4, [Reply] = @p5

WHERE ([ID] = @p0) AND ([UserName] = @p1) AND ([PostTime] = @p2) AND ([Message] = @p3) AND (NOT ([IsReplied] = 1)) AND ([Reply] IS NULL)

-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [00000000-0000-0000-0000-000000000000]

-- @p1: Input String (Size = 4; Prec = 0; Scale = 0) [ghgh]

-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [2007-8-16 10:20:09]

-- @p3: Input String (Size = 3; Prec = 0; Scale = 0) [ghj]

-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [True]

-- @p5: Input String (Size = 3; Prec = 0; Scale = 0) [qqq]

-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20706.1

 

DELETE FROM [dbo].[tbGuestBook] WHERE ([ID] = @p0) AND ([UserName] = @p1) AND ([PostTime] = @p2) AND ([Message] = @p3) AND (NOT ([IsReplied] = 1)) AND ([Reply] = @p4)

-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [158ec941-13ff-4093-bd8b-9fceae152171]

-- @p1: Input String (Size = 2; Prec = 0; Scale = 0) [44]

-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [2007-8-16 9:56:19]

-- @p3: Input String (Size = 2; Prec = 0; Scale = 0) [44]

-- @p4: Input String (Size = 3; Prec = 0; Scale = 0) [222]

-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.20706.1

 

       今天就讲到这里,下次将系统介绍查询句法。

posted on 2013-08-09 14:19  wuzx-blog  阅读(285)  评论(0编辑  收藏  举报