【问题标题】:Exception: Cannot add an entity that already exists using linqtosql例外:无法使用 linqtosql 添加已存在的实体
【发布时间】:2015-02-18 20:26:33
【问题描述】:

在网页中,我使用了一些添加在按钮上的 html 控件(文本框)。使用 for 循环我计算这些控件并将它们的数据插入数据库但是当进程开始时只插入前两条记录然后抛出这个异常。除了 sr.no 和自动编号并且它也是主键的列之外,所有列都存在于代码中。

protected void _btnSendRequest_Click(object sender, EventArgs e)
        {
            using (CertDataContext context = new CertDataContext())
            {  
                Tech_Request_File j = new Tech_Request_File();

                for (int i = 0; i < Request.Form.Count; i++)
                {
                    string FileName = "_txtFileName" + i;
                    string FileValue = Request.Form[FileName];

                    string FilePath = "_txtFilePath" + i;
                    string PathValue = Request.Form[FilePath];

                    if (FileValue != null && PathValue != null)
                    {
                        j.user_id = Convert.ToInt32(_txtID.Text);
                        j.incident_id = Convert.ToInt32(_txtIncidentID.Text);
                        j.status = 1;
                        j.tech_id = Convert.ToInt32(Request.QueryString["id"]);
                        j.file_name = FileValue;
                        j.file_path = PathValue;

                        try
                        {
                            context.Tech_Request_Files.InsertOnSubmit(j);
                            context.SubmitChanges();
                        }
                        catch (Exception ex)
                        {
                            Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\" " + ex.Message + "<br />" + ex.Source + "<br />" + ex.InnerException + "<br />" + ex.HResult + " \")</SCRIPT>");
                        }

                    }

                    else
                    {
                        Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\" Request sent successfully. \")</SCRIPT>");
                        break;
                    }
                }
            }

【问题讨论】:

    标签: c# asp.net linq linq-to-sql


    【解决方案1】:

    您正尝试在您的 for 循环中重复填充和插入相同的 Tech_Request_File 实例。您只需为循环中的每个迭代实例化一个新的Tech_Request_File实体:

    罢工>

    Tech_Request_File j = new Tech_Request_File();
    

    for (int i = 0; i < Request.Form.Count; i++)
    {
        Tech_Request_File j = new Tech_Request_File();
        // ...
    

    【讨论】:

    • 我会在 5 分钟后将其标记为答案...非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多