linq的创建 和 数据的增删改查

Posted 王炜忠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linq的创建 和 数据的增删改查相关的知识,希望对你有一定的参考价值。

1.linq创建之前,一定要在sql做好数据表的主外键关系。

2.linq文件是以.dbml结尾,一般一个数据库的名字就是一个linq的名字

3,以实例来演示增删改查

数据库的名字为linq,里面有两个表Users(UserName,Password,Sex,NickName,Birthday,Nation)和Nation(NationCode,NationName)

(1)创建名为linq的linq。

创建完之后啥也不用改,如果需要在重新封装类和数据扩展,那就想以前重新建立Users和UserData,只需要把需要重新封装和扩展的部分写上,在这之前一定要在总类面前加上Partial,如下

(2)继续封装类(注意partial)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Users 的摘要说明
/// </summary>
public partial class Users
{

    public string SexStr
    {
        get {
            string a = "<空>";
            if (_Sex != null)
            {
              a=Convert.ToBoolean(_Sex) ? "" : "";
            }
            return a;
        }
    
    }
    public string NA
    {
        get {
            return this.Nation1.NationName;
        
        }
    }



}
View Code

(3)建立方法(linq的增删改查方法)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// UsersDate 的摘要说明
/// </summary>
public class UsersDate
{
    linqDataContext cnn = null;
    public UsersDate()
    {
        cnn = new linqDataContext();
    }
    /// <summary>
    /// 查询全部信息
    /// </summary>
    /// <returns>泛型集合</returns>
    public List<Users> quan()
    {

        return cnn.Users.ToList();//如果没有数据,返回一个count=0的泛型集合
    }
   
    /// <summary>
    /// 删除UserName=uname的整条数据
    /// </summary>
    /// <param name="uname">名称</param>
    /// <returns>bool类型</returns>
    public bool delete(string uname)
    {
        bool a = false;
        Users u = cnn.Users.Where(r => r.UserName==uname).FirstOrDefault();
        if (u != null)
        {
            cnn.Users.DeleteOnSubmit(u);
            cnn.SubmitChanges();
            a = true;
        }
        return a;
    }
    /// <summary>
    /// 查询单条数据
    /// </summary>
    /// <param name="uname">名字</param>
    /// <returns>对象</returns>
    public Users dan(string uname)
    {
        Users u = cnn.Users.Where(r => r.UserName == uname).FirstOrDefault();
        return u;
    }
    /// <summary>
    /// 修改数据信息
    /// </summary>
    /// <param name="u">需要改的内容</param>
    /// <returns>bool类型</returns>
    public bool update(Users u)
    {
        bool a = false;
        Users uu = cnn.Users.Where(r => r.UserName == u.UserName).FirstOrDefault();
        if (uu != null)
        {
            uu.Password = u.Password;
            uu.NickName = u.NickName;
            uu.Sex = u.Sex;
            uu.Birthday = u.Birthday;
            uu.Nation = u.Nation;
        }
        try
        {
            cnn.SubmitChanges();
            a = true;
        }
        catch { }
        return a;
    }
    /// <summary>
    /// 插入数据
    /// </summary>
    /// <param name="u">对象</param>
    /// <returns>bool值</returns>
    public bool insert(Users u)
    {
        bool a = false;
        cnn.Users.InsertOnSubmit(u);
        try
        {
            cnn.SubmitChanges();
            a = true;
        }
        catch { }
        return a;
    }



}
View Code

LINQ 的First 和 FirstOrDefault方法:

First()返回结果集中第一个匹配的元素,如果找不到会发生异常;

FirstOrDefault()返回结果集中第一个匹配的,如果找不到会返回空。  

 

(4)主界面和功能

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Repeater ID="Repeater1" runat="server">
            <HeaderTemplate>
                <table style="width:100%; text-align:center">
                    <tr style="background-color:blue;">
                    <td>姓名</td>
                    <td>密码</td>
                    <td>性别</td>
                    <td>昵称</td>
                    <td>生日</td>
                    <td>民族</td>
                    <td>操作</td>
                        </tr>
            </HeaderTemplate>
            <ItemTemplate>
                  <tr style="background-color:gray;">
                    <td><%#Eval("UserName") %></td>
                    <td><%#Eval("Password") %></td>
                    <td><%#Eval("SexStr") %></td>
                    <td><%#Eval("NickName") %></td>
                    <td><%#Eval("Birthday","{0:yyyy年MM月dd日}") %></td>
                    <td><%#Eval("NA") %></td>
                      <td>
                          <a href="delete.aspx?uname=<%#Eval("UserName") %>">删除</a>&nbsp;&nbsp;&nbsp;
                          <a href="update.aspx?uname=<%#Eval("UserName") %>" target="_blank">修改</a>
                      </td>
                        </tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
            
        </asp:Repeater>
        <a href="insert.aspx" target="_blank">添加新数据</a>
    </form>
</body>
</html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            Repeater1.DataSource = new UsersDate().quan();
            Repeater1.DataBind();
        }

    }
}
View Code

(5)删除界面的代码(删除界面不用布局,什么也没写)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class delete : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string uname=Request["uname"];//在delete.aspx页面接uanme
        bool a = new UsersDate().delete(uname);
        if (a)
        {
            Response.Write("<script>");
            Response.Write("alert(\'删除成功\');");
            Response.Write("window.location.href=\'Default.aspx\';");
            Response.Write("</script>");

        }
        else
        {
            Response.Write("<script>");
            Response.Write("alert(\'删除失败\');");
            Response.Write("window.location.href=\'Default.aspx\';");
            Response.Write("</script>");
        }


    }
}
View Code

(6)插入界面的布局和代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="insert.aspx.cs" Inherits="insert" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     姓名<asp:TextBox ID="uname_Text" runat="server"></asp:TextBox>
        <asp:Label ID="unameerror_label" runat="server" Text=""></asp:Label><br />
    密码<asp:TextBox ID="pwd1_Text" runat="server" TextMode="Password"></asp:TextBox>
        <asp:Label ID="pwd1errpr_Label" runat="server" Text="Label"></asp:Label><br />
    确认密码<asp:TextBox ID="pwd2_Text" runat="server" TextMode="Password"></asp:TextBox><br />
        性别<asp:RadioButtonList ID="RadioButtonList1" runat="server" Width="106px" RepeatDirection="Horizontal">
            <asp:ListItem Value="true" Selected="True">男</asp:ListItem>
            <asp:ListItem Value="false">女</asp:ListItem>
        </asp:RadioButtonList>
    昵称<asp:TextBox ID="nickname_TextBox" runat="server"></asp:TextBox>
        <asp:Label ID="nicknameerror_Label" runat="server" Text="Label"></asp:Label><br />
   生日<asp:DropDownList ID="year_dd" runat="server" AutoPostBack="false"></asp:DropDownList>
        <asp:DropDownList ID="month_dd" runat="server"  AutoPostBack="false"></asp:DropDownList>
        <asp:DropDownList ID="day_dd" runat="server"  AutoPostBack="false"></asp:DropDownList><br />
   民族<asp:DropDownList ID="nation_dd" runat="server"></asp:DropDownList><br />

        <asp:Button ID="enter" runat="server" Text="确定" />
    </div>
    </form>
</body>
</html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class insert : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {



            for (int i = 2006; i >= 1990; i--)
            {
                year_dd.Items.Add(new ListItem(i.ToString(), i.ToString()));

            }
            for (int i = 12; i >= 1; i--)
            {
                month_dd.Items.Add(new ListItem(i.ToString(), i.ToString()));

            }
            for (int i = 31; i >= 1; i--)
            {
                day_dd.Items.Add(new ListItem(i.ToString(), i.ToString()));

            }
            nation_dd.DataSource = new NationData().quan();
            nation_dd.DataTextField = "NationName";
            nation_dd.DataValueField = "NationCode";
            nation_dd.DataBind();





        }
        enter.Click += enter_Click;
    }

    void enter_Click(object sender, EventArgs e)
    {
        Users uu = new Users();
        Users u = new UsersDate().dan(uname_Text.Text);
        if (u != null)
        {
            unameerror_label.Text = "该用户名已被占用";
            return;
        }
        unameerror_label.Text = "";
        uu.UserName = uname_Text.Text;
        uu.Password = pwd1_Text.Text;
        uu.NickName = nickname_TextBox.Text;
        uu.Sex = Convert.ToBoolean(RadioButtonList1.SelectedValue);
        uu.Birthday = Convert.ToDateTime(year_dd.SelectedValue+"-"+month_dd.SelectedValue+"-"+day_dd.SelectedValue);
        uu.Nation = nation_dd.SelectedValue;
        bool a = new UsersDate().insert(uu);
        if (a)
        {
            Response.Write("<script>");
            Response.Write("alert(\'插入成功\');");
            Response.Write("window.opener.location.href=\'Default.aspx\';");
            Response.Write("window.close();");
            Response.Write("</script>");
        }
        else
        {
            Response.Write("<script>");
            Response.Write("alert(\'插入失败\');");
            Response.Write("</script>");
        }



    }
}
View Code

(7)修改界面的布局和代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="update.aspx.cs" Inherits="update" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    姓名<asp:TextBox ID="uname_Text" runat="server"></asp:TextBox><br />
    密码<asp:TextBox ID="pwd1_Text" runat="server" TextMode="Password"></asp:TextBox>
        <asp:Label ID="pwd1errpr_Label" runat="server" Text="Label"></asp:Label><br />
    确认密码<asp:TextBox ID="pwd2_Text" runat="server" TextMode="Password"></asp:TextBox><br />
        性别<asp:RadioButtonList ID="RadioButtonList1" runat="server" Width="106px" RepeatDirection="Horizontal">
            <asp:ListItem Value="true">男</asp:ListItem>
            <asp:ListItem Value="false">女</asp:ListItem>
        </asp:RadioButtonList>
    昵称<asp:TextBox ID="nickname_TextBox" runat="server"></asp:TextBox>
        <asp:Label ID="nicknameerror_Label" runat="server" Text="Label"></asp:Label><br />
   生日<asp:DropDownList ID="year_dd" runat="server" AutoPostBack="false"></asp:DropDownList>
        <asp:DropDownList ID="month_dd" runat="server"  AutoPostBack="false"></asp:DropDownList>
        <asp:DropDownList ID="day_dd" runat="server"  AutoPostBack="false"></asp:DropDownList><br />
   民族<asp:DropDownList ID="nation_dd" runat="server"></asp:DropDownList><br />

        <asp:Button ID="enter" runat="server" Text="确定" />
    </div>
    </form>
</body>
</html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class update : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Users u = new UsersDate().dan(Request["uname"]);
            if (u != null)
            {
                uname_Text.Text = u.UserName;
                if (u.Sex==null)
                { }
                else
                {
                    if (u.Sex == true)
                    {
                        RadioButtonList1.Items[0].Selected = true;
                    }
                    else
                    {
                        RadioButtonList1.Items[1].Selected = true;
                    }

                }
              
                nickname_TextBox.Text = u.NickName;
                for (int i = 2006; i >= 1990; i--)
                {
                    year_dd.Items.Add(new ListItem(i.ToString(),i.ToString()));
                
                }
                for (int i = 12; i >= 1; i--)
                {
                    month_dd.Items.Add(new ListItem(i.ToString(), i.ToString()));

                }
                for (int i = 31; i >= 1; i--)
                {
                    day_dd.Items.Add(new ListItem(i.ToString(), i.ToString()));

                }
                nation_dd.DataSource = new NationData().quan();
                nation_dd.DataTextField = "NationName";
                nation_dd.DataValueField = "NationCode";
                nation_dd.DataBind();
                year_dd.SelectedValue = u.Birthday.Value.Year.ToString();
                month_dd.SelectedValue = u.Birthday.Value.Month.ToString();
                day_dd.SelectedValue = u.Birthday.Value.Day.ToString();
                nation_dd.SelectedValue = u.Nation;
            }
        
        
        
        }
        enter.Click += enter_Click;



    }

    void enter_Click(object sender, EventArgs e)
    {
        Users u = new Users();
        u.UserName = uname_Text.Text;
        u.Password = pwd1_Text.Text;
        u.NickName = nickname_TextBox.Text;
        u.Sex = Convert.ToBoolean(RadioButtonList1.SelectedValue);
        u.Birthday = Convert.ToDateTime(year_dd.SelectedValue+"-"+month_dd.SelectedValue+"-"+day_dd.SelectedValue);
        u.Nation = nation_dd.SelectedValue;
        bool a = new UsersDate().update(u);
        if (a)
        {
            Response.Write("<script>");
            Response.Write("alert(\'修改成功\');");
            Response.Write("window.opener.location.href=\'Default.aspx\';");
            Response.Write("window.close();");
            Response.Write("</script>以上是关于linq的创建  和   数据的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Linq to SQL 的增删改查操作

2017-06-01Linq基础+Lambda表达式实现对数据库的增删改查

LINQ的最简单的增删改查写法

LinQ to Sql中的增删改查

测试1.书店的增删改查项目.链接数据库

winform 用linq to SQL 类实现数据库的增删改查 2016年02月18日