异常:无法使用 linqtosql 添加已存在的实体

Exception: Cannot add an entity that already exists using linqtosql

在一个网页中,我使用了一些添加到按钮上的 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;
                    }
                }
            }

您正试图在 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();
    // ...