如何处理 asp.net 网络应用程序中的 "Violation of UNIQUE KEY constraint" 异常

How to handle "Violation of UNIQUE KEY constraint" exception in asp.net web application

<AlternatingRowStyle BackColor="#F7F7F7" HorizontalAlign="Justify" Wrap="False" />
        <Columns>
            <asp:CommandField ShowDeleteButton="True"   ButtonType="Image" />
            <asp:CommandField ShowEditButton ="True" ButtonType="Image" />
            <asp:TemplateField HeaderText="Name" SortExpression="Name">

                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Email" SortExpression="Email">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Occupation" SortExpression="Occupation">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Occupation") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Occupation") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

             <asp:TemplateField HeaderText="Role" SortExpression="Role">
                <EditItemTemplate>
                    <asp:DropdownList ID="Roles"  runat="server" Text='<%# Bind("Roles") %>'>
                       <asp:ListItem Selected="True"    Text="User" value="User"></asp:ListItem>
                       <asp:ListItem Selected="False"   Text="Admin" value="Admin"></asp:ListItem>
                        </asp:DropdownList>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server" Text='<%# Bind("Roles") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Address" SortExpression="Address">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Mobile" SortExpression="Mobile">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Mobile") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle HorizontalAlign="Center" Wrap="False" />
        <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
        <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
        <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
        <SortedAscendingCellStyle BackColor="#F4F4FD" />
        <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
        <SortedDescendingCellStyle BackColor="#D8D8F0" />
        <SortedDescendingHeaderStyle BackColor="#3E3277" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:UsTravelConnectionString %>" 
        DeleteCommand="DELETE FROM [Users] WHERE [Id] = @Id" 
        InsertCommand="INSERT INTO [Users] ([Name], [Email], [Occupation],[Roles], [Address], [Mobile]) VALUES (@Name, @Email, @Occupation,@Roles, @Address, @Mobile)"
         SelectCommand="SELECT [Name], [Email], [Occupation],[Roles], [Address], [Mobile], [Id] FROM [Users]"
         UpdateCommand="UPDATE [Users] SET [Name] = @Name, [Email] = @Email, [Occupation] = @Occupation, [Roles]=@Roles, [Address] = @Address, [Mobile] = @Mobile WHERE [Id] = @Id">
        <DeleteParameters>
            <asp:Parameter Name="Id" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="Occupation" Type="String" />
            <asp:Parameter Name="Roles" Type="String" />
            <asp:Parameter Name="Address" Type="String" />
            <asp:Parameter Name="Mobile" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="Name" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="Occupation" Type="String" />
            <asp:Parameter Name="Roles" Type="String" />
            <asp:Parameter Name="Address" Type="String" />
            <asp:Parameter Name="Mobile" Type="String" />
            <asp:Parameter Name="Id" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <br />
<p runat="server" id="noRowsMsg" sytle="display:none"></p>
</form>

Email 字段在表中具有唯一键约束。我在处理异常和输出用户友好消息时遇到困难,该消息通知在更新电子邮件时更新新 EmailID

一种可能的方法是在 "Insert Click" 和实际的数据库插入操作之间引入验证。

您可以通过向 Sql 数据源添加 Inserting 事件处理程序来完成此操作。

OnInserting="SqlDataSource_Inserting"

完成后,将处理程序定义为:

protected void SqlDataSource_Inserting(object sender, SqlDataSourceCommandEventArgs e) 
{      
    var emailToBeInserter = e.Command.Parameters["@Email"].Value;

    // do a DB lookup call and validate if it is unique.
    // if not unique, cancel the Insert and display an error message.
    e.Cancel = true; // if email already exists in DB.

    // if unique, do nothing.
}

进行显式验证会产生额外的数据库调用成本,但通常比让 "INSERT" 逻辑 运行 通过并抛出 "Unique key" 和其他此类异常更好。