防止多个重复数据输入实体数据库(已关闭) [英] Prevent multiple duplicate data entry into entities database(Closed)

查看:78
本文介绍了防止多个重复数据输入实体数据库(已关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在插入数据库时​​防止重复数据输入实体数据库。目前这是我要插入数据库的代码。我在网上检查了很多帖子,但由于使用起来似乎真的不一样,因此不确定使用哪个。我试图防止重复输入PatientIc并显示错误消息。

I am trying to prevent a duplicate data entry into the entity database when inserting into the database. Currently heres my code for inserting into database. I have check many post online but not really sure which one to use as it seems really different. I am trying to prevent duplicate entry for PatientIc and display an error message for it. Thanks in advance!

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>


推荐答案

可以做的就是在保存gridview之前将数据放入数据库后,您可以调用某些服务(一种返回布尔值的方法)。该服务/方法将带有一个参数(PatientIc),并将检查相应的表是否存在任何记录。

What you can do is just before you are saving gridview data into a DB, you can call certain service (a method that returns a bool value). This service/method will take an argument (PatientIc) and will check the corresponding table if any record exits or not. If there record is found skip insert else insert new.

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);
    }
}

这篇关于防止多个重复数据输入实体数据库(已关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆