Haider Khattak
Haider Khattak

Reputation: 577

Exception: Cannot add an entity that already exists using linqtosql

in a webpage i am using some html controls(textboxes) which adds on a button. using for loop i count those controls and inserts their data into the database but when the process starts only the first two records are inserted anthen this exception is thrown. All the columns are present in the code except one which is sr.no and autonumbered and it is the primary key as well.

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

Upvotes: 0

Views: 641

Answers (1)

Douglas
Douglas

Reputation: 54887

You are attempting to populate and insert the same Tech_Request_File instance repeatedly in your for loop. You just need to instantiate a new Tech_Request_File entity for each iteration within your loop:

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();
    // ...

Upvotes: 1

Related Questions