Awais Mahmood
Awais Mahmood

Reputation: 1336

The property 'PK' is part of the object's key information and cannot be modified. Error occurs after some successful data entry

I have checked other posts with the related error but in my case it is different since it successfully allows first iteration and occurs in the second iteration of the loop. I am using DataBase first approach in MVC application. In the following code:

ACOD a = new ACOD();
int cd = 1;
foreach (var t in e)
{
    a.S1 = t.S1;
    a.S2 = t.S2;
    a.S39 = t.S39;
    a.S40 = t.S40;

    if (db.ACODs.ToList().Count != 0)
    {
         var td = db.ACODs.Max(x => x.N100);
         cd = Convert.ToInt32(td) + 1;
    }
    a.N100 = cd;

    db.ACODs.Add(a);
    db.SaveChanges();
}

N100 is my primary key. I am getting the above mentioned error in the second time the loop iterates. I have disabled the auto entry of N100 so I am generating PK in my code. The loop successfully runs for N100 = 1 but in the second iteration when N100 = 2, the above mentioned error occurs on Add(a) method call.

Where am I wrong? I am using the same methodologies for adding data in similar tables but never got this error.

Upvotes: 0

Views: 557

Answers (1)

Najkin
Najkin

Reputation: 932

The problem seems to be that you create only one instance of ACOD and that you reuse it. For EF, after the first iteration of the loop, you're not adding new entities, you're modifying an existing one.

Try to put the line ACOD a = new ACOD(); inside the loop, that should fix your problem.

Upvotes: 2

Related Questions