如何通过后面的代码将值插入或更新到DB中

时间:2013-04-24 11:00:44

标签: c# asp.net sql-server repeater

我目前正在为我的网站开发管理页面。目前,我正在尝试开发用户卷和规则。

我的数据库结构如下:


tblSiteUserRolls

id
rollName
rollDescription

tblSiteRollAccess

id
accessName
accessDescription

tblSiteRollLink

id
rollId
rollAccessId
allowed

tblSiteMemberDetail

~stuff~
userRollId

我手动添加了rollsrollAccess,并将其显示在Repeater控件上,名称旁边的复选框很少。这一切目前都完美无缺。

这可以通过将所有rollAccess添加到通用列表,并将allowed的所有值设置为0来实现。然后检查选择的的所有rollAccess来自 tblSiteRollLink roll,如果在那里,请将allowed设置为1。

是否可以通过编辑的值快速插入或更新 tblSiteRollLink 中的记录,而不是遍历repeater中的所有值并手动执行此操作?

这是一些代码: Page.aspx

<asp:Repeater ID="rptRollRules" runat="server">
        <HeaderTemplate>
            Roll Rules
            <table>
                <tr>
                    <th>Access Name
                    </th>
                    <th>Allowed
                    </th>
                </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label ID="lblRollId" runat="server" Text='<%# Eval("RollId") %>' Visible="False"></asp:Label>
                    <asp:Label ID="lblAccessId" runat="server" Text='<%# Eval("AccessId") %>' Visible="False"></asp:Label>
                    <asp:Label ID="lblAccessName" runat="server" Text='<%# Eval("AccessName") %>'></asp:Label>
                </td>
                <td>
                    <asp:CheckBox ID="chkIsAllowed" runat="server" Checked='<%# Eval("AccessAllowed") %>'/>
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:Repeater>

Page.cs

private void PopulateRollRulesRepeater(string rollId)
    {
        // Get all the access rolls
        List<RollAccess> access = new List<RollAccess>();

        string strSql = "SELECT [id]" +
                              ", [accessName]" +
                              ", [accessDescription]" +
                              " FROM tblSiteRollAccess";

        SqlCommand sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text };

        SqlDataReader rdr = sqlComm.ExecuteReader();

        while (rdr.Read())
        {
            access.Add(new RollAccess
                {
                    RollId = rollId,
                    AccessId = rdr["id"],
                    AccessName = rdr["accessName"],
                    AccessDescription = rdr["accessDescription"],
                    AccessAllowed = false
                });
        }

        rdr.Close();
        DataConn.Disconnect();

        // Check if the current roll has the access
        strSql = "SELECT [rollAccessId]" +
                 ", [allowed]" +
                 " FROM vwGetRollAccess WHERE rollID = @id AND allowed = 1";

        sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text };
        sqlComm.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = rollId;

        rdr = sqlComm.ExecuteReader();

        while (rdr.Read())
        {
            foreach (RollAccess rollAccess in access.Where(rollAccess => rollAccess.AccessId.ToString() == rdr["rollAccessId"].ToString()))
            {
                rollAccess.AccessAllowed = true;
            }
        }

        rdr.Close();
        DataConn.Disconnect();

        rptRollRules.DataSource = access;
        rptRollRules.DataBind();
    }

    public class RollAccess
    {
        public object RollId { get; set; }
        public object AccessId { get; set; }
        public object AccessName { get; set; }
        public object AccessDescription { get; set; }
        public object AccessAllowed { get; set; }
    }

/// <summary>
/// Update the Roll's details and access levels
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpdate_Click(object sender, EventArgs e)
{

    DataTable rules = new DataTable();
    DataColumn rollId = new DataColumn("rollId", typeof(int));
    DataColumn rollAccessId = new DataColumn("rollAccessId", typeof(int));
    DataColumn allowed = new DataColumn("allowed", typeof(int));

    rules.Columns.Add(rollId);
    rules.Columns.Add(rollAccessId);
    rules.Columns.Add(allowed);

    DataRow drRules = rules.NewRow();

    // Update the access levels
    foreach (RepeaterItem i in rptRollRules.Items)
    {
        //Retrieve the state of the CheckBox
        CheckBox chkIsAllowed = (CheckBox) i.FindControl("chkIsAllowed");
        Label lblRollId = (Label) i.FindControl("lblRollId");
        Label lblAccessId = (Label) i.FindControl("lblAccessId");

        drRules["rollId"] = lblRollId.Text;
        drRules["rollAccessId"] = lblAccessId.Text;
        drRules["allowed"] = chkIsAllowed.Checked.GetHashCode();
    }

    string strSql = "";
}

/ Current / SQL

-- =============================================
-- Author:      Darren Whitfield
-- Create date: 24 April 2013
-- Description: This will update the user roll rules
-- =============================================

CREATE TABLE [rulesTable]
( 
     [ID] [int] NOT NULL PRIMARY KEY IDENTITY,
     [rollId] [int] NOT NULL, 
     [rollAccessId] [int] NOT NULL, 
     [allowed] [tinyint] NOT NULL
)
CREATE TYPE [rulesUDT] AS TABLE
( 
     [rollId] [int] NOT NULL, 
     [rollAccessId] [int] NOT NULL, 
     [allowed] [tinyint] NOT NULL
)

GO

CREATE PROCEDURE procUpdateUserRollRules 
@tbl rulesUDT READONLY
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO [rulesTable] SELECT * FROM @tbl

END
GO

1 个答案:

答案 0 :(得分:0)

根据您完成中间层的方式,这应该是可能的。

您需要将值列表作为表传递给SQL Server,并将其传递给接受表类型参数的存储过程:http://msdn.microsoft.com/en-us/library/bb510489.aspx

在该存储过程中,您可以使用MERGE命令在单个操作中进行INSERT / UPDATE:http://msdn.microsoft.com/en-GB/library/bb510625.aspx

以下是此网站上另一个问题的C#示例Passing datatable from C# to SQL Server 2008

好的查看你的代码示例的回发,一些伪代码:

    // Update the access levels
    foreach (RepeaterItem i in rptRollRules.Items)
    {

DataRow drRules = rules.NewRow(); //One table row per repeater row

        //Retrieve the state of the CheckBox
        CheckBox chkIsAllowed = (CheckBox) i.FindControl("chkIsAllowed");
        Label lblRollId = (Label) i.FindControl("lblRollId");
        Label lblAccessId = (Label) i.FindControl("lblAccessId");

        drRules["rollId"] = lblRollId.Text;
        drRules["rollAccessId"] = lblAccessId.Text;
        drRules["allowed"] = chkIsAllowed.Checked.GetHashCode();

rules.Rows.Add(drRules); //Add your row to the data table
    }

cmd = new SqlCommand(); //Can't remember the syntax
cmd.CommandText = "EXEC YourMergeStoredProcedure @YourDataTable";
SqlParameter sqlParameter = cmd.Parameters.AddWithValue("@YourDataTable", drRules);
sqlParameter.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();

不要忘记,您需要在SQL Server中创建表类型,以便它知道会发生什么。请参阅上面的链接以了解如何执行此操作。另外我的代码只是为了给你一个想法,我在这里写下我的头脑,所以会有错误。