I've tried few things:
- Attaching data into Context
- Manually modifying edmx file (here is the source)
- Manually getting the ForeignKey Object by (
data.RTMS_GsmOperator = Context.RTMS_GsmOperator.FirstOrDefault(c => c.Id == data.GsmOperatorId);
) and then SaveChanges
Here is the code for the Option 1:
data.Id = GetMaxId(data)
Context.Attach(data); //Here I attached it
Context.RTMS_PackageApplication.AddObject(data);
Context.SaveChanges(); //I get the error here
Here is the code for the Option 3:
data.Id = GetMaxId(data)
data.RTMS_GsmOperator = Context.RTMS_GsmOperator.FirstOrDefault(c => c.Id == data.GsmOperatorId); //Here
data.RTMS_Machine = Context.RTMS_Machine.FirstOrDefault(c => c.Id == data.MachineId); //Here
Context.RTMS_PackageApplication.AddObject(data);
Context.SaveChanges(); //I get the error here
None above worked!
NOTE: NONE of the Id's are auto-incremental.
When I run the code below:
public RTMS_PackageApplication Insert(RTMS_PackageApplication data)
{
using (var Context = base.RtmsEntites)
{
//Since, its not auto-incremental, I do it manually.
data.Id = GetMaxId(data)
Context.RTMS_PackageApplication.AddObject(data);
Context.SaveChanges(); //I get the error here
}
}
Error:
Violation of PRIMARY KEY constraint 'PK_GsmOperator'. Cannot insert duplicate key in object 'dbo.RTMS_GsmOperator'. The duplicate key value is (1).
The statement has been terminated.
If you must know here is the GetMaxId
method:
private int GetMaxId(RTMS_PackageApplication data)
{
int Result = 1;
var Temp =
base.RtmsEntites.RTMS_PackageApplication.AsQueryable().OrderByDescending(u => u.Id).
FirstOrDefault();
if (Temp != null)
Result = Temp.Id + 1;
return Result;
}
As for the auto-incremental; the problem is on the GsmOperatorId
(Foreign Key data table) and the data is ALREADY there, I just want to add the Id into PackageApplciation
Table. So, I'm NOT trying to add new GsmOperator
only PackageApplication
The EF is trying to INSERT GsmOperator and Machine entities as well. But why? I even re-attached it as in one of the answeres below.
How can I fix this?