防止多个重复数据输入实体数据库(已关闭)

时间:2017-02-06 07:31:09

标签: c# asp.net database

我正在尝试阻止在插入数据库时​​将重复数据输入到实体数据库中。目前继承我插入数据库的代码。我在线检查了很多帖子,但不确定使用哪一个,因为它看起来真的不同。我正在尝试阻止PatientIc重复输入并显示错误消息。提前谢谢!

protected void myGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //Insert new Prescription
    if (e.CommandName == "Insert")
    {
        Page.Validate("Add");
        if (Page.IsValid)
        {
            var fRow = myGridview.FooterRow;
            TextBox txtPatientName = (TextBox)fRow.FindControl("txtPatientName");
            TextBox txtPatientIC = (TextBox)fRow.FindControl("txtPatientIc");
            TextBox txtQuantity = (TextBox)fRow.FindControl("txtQuantity");
            DropDownList ddType = (DropDownList)fRow.FindControl("ddType");
            DropDownList ddState = (DropDownList)fRow.FindControl("ddState");
            using (CareGiverEntities dc = new CareGiverEntities())
            {
                dc.Contacts.Add(new Contact
                {
                    PatientName = txtPatientName.Text.Trim(),
                    PatientIc= txtPatientIC.Text.Trim(),
                    Quantity = txtQuantity.Text.Trim(),
                    MedicineTypeID = Convert.ToInt32(ddType.SelectedValue),
                    MedicineID = Convert.ToInt32(ddState.SelectedValue),
                    DatePrecribed= DateTime.Now
                });
                dc.SaveChanges();
                PopulateContacts();
            }
        }
    }
}

网格视图代码

<asp:GridView ID="myGridview" runat="server" AutoGenerateColumns="false"
    DataKeyNames="ContactID,MedicineTypeID,MedicineID" CellPadding="10" CellSpacing="0"
    ShowFooter="true" CssClass="myGrid"  HeaderStyle-CssClass="header" RowStyle-CssClass="trow1" 
    AlternatingRowStyle-CssClass="trow2" OnRowCommand="myGridview_RowCommand" OnRowCancelingEdit="myGridview_RowCancelingEdit" OnRowDeleting="myGridview_RowDeleting" OnRowEditing="myGridview_RowEditing" OnRowUpdating="myGridview_RowUpdating" AllowPaging="True" AllowSorting="True" >
    <EmptyDataTemplate>No results found.</EmptyDataTemplate> 
    <Columns>
        <asp:TemplateField SortExpression="FullName">
            <HeaderTemplate>Patient Name</HeaderTemplate>
            <ItemTemplate><%#Eval("PatientName") %></ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtPatientName" runat="server" Text='<%#Bind("PatientName") %>' />
                <asp:RequiredFieldValidator ID="rfCPEdit" runat="server" ForeColor="Red" ErrorMessage="*"
                    Display="Dynamic" ValidationGroup="edit" ControlToValidate="txtPatientName">Required</asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtPatientName" runat="server"></asp:TextBox><br />
                <asp:RequiredFieldValidator ID="rfCP" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtPatientName">Required</asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>Patient IC</HeaderTemplate>
            <ItemTemplate><%#Eval("PatientIc") %></ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtPatientIc" runat="server" Text='<%#Bind("PatientIc") %>' />
                <asp:RequiredFieldValidator ID="rfCOEdit" runat="server" ForeColor="Red" ErrorMessage="*"
                    Display="Dynamic" ValidationGroup="edit" ControlToValidate="txtPatientIc">Required</asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtPatientIc" runat="server"></asp:TextBox><br />
                <asp:RequiredFieldValidator ID="rfCO" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtPatientIC">Required</asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>Quantity</HeaderTemplate>
            <ItemTemplate><%#Eval("Quantity") %></ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtQuantity" runat="server" Text='<%#Bind("Quantity") %>' />
                <asp:RequiredFieldValidator ID="rfCNEdit" runat="server" ErrorMessage="*"
                    Display="Dynamic" ForeColor="Red" ValidationGroup="edit" ControlToValidate="txtQuantity">Required</asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox><br />
                <asp:RequiredFieldValidator ID="rfCN" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtQuantity">Required</asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>Medicine Type</HeaderTemplate>
            <ItemTemplate><%#Eval("MedicineType") %></ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="ddType" runat="server" AutoPostBack="true" 
                    OnSelectedIndexChanged="ddCountry_SelectedIndexChanged">
                    <asp:ListItem Text="Select Medicine type" Value="0"></asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfCEdit" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddType" InitialValue="0">Required
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:DropDownList ID="ddType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddCountry_SelectedIndexChanged">
                    <asp:ListItem Text="Select Medicine Type" Value="0"></asp:ListItem>
                </asp:DropDownList>
                <br />
                <asp:RequiredFieldValidator ID="rfC" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddType" InitialValue="0">Required</asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>Medicine Name</HeaderTemplate>
            <ItemTemplate><%#Eval("MedicineName") %></ItemTemplate>
            <EditItemTemplate>
                <asp:DropDownList ID="ddState" runat="server">
                    <asp:ListItem Text="Select Medicine" Value="0"></asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfSEdit" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddState" InitialValue="0">
                    Required
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:DropDownList ID="ddState" runat="server">
                    <asp:ListItem Text="Select Medicine" Value="0"></asp:ListItem>
                </asp:DropDownList><br />
                <asp:RequiredFieldValidator ID="rfS" runat="server" ErrorMessage="*"
                    ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddState"
                        InitialValue="0">Required</asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lbEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                    &nbsp;|&nbsp;
                <asp:LinkButton ID="lbDelete" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you confirm?')">Delete</asp:LinkButton>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="lbUpdate" runat="server" CommandName="Update" ValidationGroup="edit">Update</asp:LinkButton>
                    &nbsp;|&nbsp;
                <asp:LinkButton ID="lbCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btnInsert" runat="server" Text="Prescribe" CommandName="Insert" ValidationGroup="Add" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

3 个答案:

答案 0 :(得分:1)

在插入之前进行检查,记录是否已存在可能会解决您的重复问题。

答案 1 :(得分:1)

我猜你不想将PatientIc设置为主键,因此,我是否可以建议在表模式本身中设置一个唯一约束。

这样您就不必从数据库中检查是否存在冗余数据。

答案 2 :(得分:0)

您可以做的就是在将gridview数据保存到数据库之前,可以调用某些服务(返回bool值的方法)。此服务/方法将采用参数(PatientIc)并将检查相应的表是否有任何记录退出。如果发现记录,则跳过插入,否则插入新的。

bool IsPatientExists = IsPatientAlreadyExists(txtPatientIC);
if (!IsPatientExists)
{
    using (CareGiverEntities dc = new CareGiverEntities())
    {
        dc.Contacts.Add(new Contact
        {
            PatientName = txtPatientName.Text.Trim(),
                PatientIc= txtPatientIC.Text.Trim(),
                Quantity = txtQuantity.Text.Trim(),
                MedicineTypeID = Convert.ToInt32(ddType.SelectedValue),
                MedicineID = Convert.ToInt32(ddState.SelectedValue),
                DatePrecribed= DateTime.Now
        });
        dc.SaveChanges();
        PopulateContacts();
    }
} 

private bool IsPatientAlreadyExists(string patientID)
{
    using (CareGiverEntities dc = new CareGiverEntities())
    {            
        return dc.Contacts.Any(x=> x.PatientIc == patientID);
    }
}