属性“ PK”是对象密钥信息的一部分,无法修改。成功输入数据后发生错误 [英] The property 'PK' is part of the object's key information and cannot be modified. Error occurs after some successful data entry

查看:58
本文介绍了属性“ PK”是对象密钥信息的一部分,无法修改。成功输入数据后发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了其他带有相关错误的帖子,但在我的情况下,这是不同的,因为它成功地允许第一次迭代并且发生在循环的第二次迭代中。我在MVC应用程序中使用数据库优先方法。在以下代码中:

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是我的主键。我在第二次循环迭代时遇到上述错误。我禁用了N100的自动输入功能,因此我在代码中生成了PK。该循环在N100 = 1时成功运行,但是在第二次迭代中,当N100 = 2时,上述错误发生在Add(a)方法调用上。

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.

推荐答案

问题似乎是您只创建了一个 ACOD 并重用它。对于EF,在循环的第一次迭代之后,您没有添加新实体,而是在修改现有实体。

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.

尝试将行 ACOD a = new ACOD(); 可以解决您的问题。

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

这篇关于属性“ PK”是对象密钥信息的一部分,无法修改。成功输入数据后发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆