Possible Duplicate:
Cannot add an entity with a key that is already in use (LINQ)
I have googled a lot on this issue and found many people facing the same issue. but could get through it yet. many solutions were posted but no gain.
I have written a LINQ query which retrieve some 38 records and using foreach loop i insert those records in other table as per the code.
var Results = (from p in (from d in compact.CURRENT_STATUS
where QtrEndDate >= d.ValidStartDate && QtrEndDate <= d.ValidDueDate && d.LocationCode == EmployeeLocation && d.DeptCode == selecteddept
select new
{
loccode = d.LocationCode,
taskcode = d.TaskCode,
deptcode = d.DeptCode,
flag = d.Flag,
startdate = d.ValidStartDate,
duedate = d.ValidDueDate,
remarks = d.Remarks,
content = d.UploadDocContent,
title = d.UploadDocTitle,
type = d.UploadDocType
}).Union(from i in compact.HISTORY_STATUS
where QtrEndDate >= i.ValidStartDate && QtrEndDate <= i.ValidEndDate && i.LocationCode == EmployeeLocation && i.DeptCode == selecteddept
select new
{
loccode = i.LocationCode,
taskcode = i.TaskCode,
deptcode = i.DeptCode,
flag = i.Flag,
startdate = i.ValidStartDate,
duedate = i.ValidEndDate.Date,
remarks = i.Remarks,
content = i.UploadDocContent,
title = i.UploadDocTitle,
type = i.UploadDocType
}) select p);
foreach (var item in Results)
{
REPORT_TABLE RT = new REPORT_TABLE();
{
RT.LocationCode = item.loccode;
RT.TaskCode = item.taskcode;
RT.DeptCode = item.deptcode;
RT.Flag = item.flag;
RT.ValidStartDate = item.startdate;
RT.ValidDueDate = item.duedate;
RT.Remarks = item.remarks;
RT.UploadDocContent = item.content;
RT.UploadDocTitle = item.title;
RT.UploadDocType = item.type;
RT.SubmittedBy = (Session["username"]).ToString();
RT.SubmittedByIP = (Session["IP"]).ToString();
RT.SubmittedOn = System.DateTime.Now;
RT.ReportID = RHqueryFind.ReportID;
RT.AsOnDate = QtrEndDate;
}
compact.REPORT_TABLEs.InsertOnSubmit(RT);
compact.SubmitChanges();
};
But i do get the error Cannot add an entity with a key that is already in use in the last line i.e SubmitChanges.
In one of the solution i found a line of code to be added as RefreshMode
but this could not solve my problem.