简体   繁体   中英

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 field has unique key constraint in tables. I am getting difficulty in handling the exception and outputting an user friendly message that informs to update a new EmailID while updating email.

one possible way is to introduce validation between the "Insert Click" and the actual DB insert action.

you can do this by adding an Inserting event handler to the Sql Data Source.

OnInserting="SqlDataSource_Inserting"

Once you have done that, define the handler as:

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.
}

Doing explicit validation has the cost of additional DB calls, but is normally a better alternative than letting the "INSERT" logic run through and throw "Unique key" and other such exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM