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

拥有回忆 提交于 2020-02-08 04:13:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/32049216/the-property-pk-is-part-of-the-objects-key-information-and-cannot-be-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!