插入重复记录LINQ

时间:2017-04-21 06:45:11

标签: c# linq

我尝试使用以下LINQ查询插入。不知何故,我收到 id 的重复记录。有人可以帮我详细说明吗?

try {
 OLA_ASSESSMENT_DTL OAD = db.OLA_ASSESSMENT_DTL.SingleOrDefault(
  ev => ev.OAD_RIV_ID == id);

 transaction = "Modify"; // resetting the value of the variable
 if (OAD == null) {
  transaction = "Add";
  OAD = new OLA_ASSESSMENT_DTL();
 }
 OAD.OAD_PER_RELAIONSHIP = relationshipfocus.relationshipfocus;
 OAD.OAD_PER_RELAIONSHIP_COMMENT = CRecHelper.CheckIsNullString(relationshipfocus.strrelationshipfocus).ToString();
 OAD.OAD_RIV_ID = id;     
 OAD.OAD_MODIFIED_DATE = DateTime.Now;
 if (transaction == "Add") {
  db.OLA_ASSESSMENT_DTL.Add(OAD);
 }
 db.SaveChanges();
}

1 个答案:

答案 0 :(得分:0)

首先,您正确检测到重复记录(尽管您可能应该使用FirstOrDefault代替SingleOrDefault,但这是一个细节):

OLA_ASSESSMENT_DTL OAD = db.OLA_ASSESSMENT_DTL.SingleOrDefault(
       ev => ev.OAD_RIV_ID == id);

transaction = "Modify"; // resetting the value of the variable
if (OAD == null)
{
    transaction = "Add";
    OAD = new OLA_ASSESSMENT_DTL();
}

但是稍后,你随意将id分配给对象,即使你知道它是重复的:

OAD.OAD_RIV_ID = id;

首先,删除该行,因为它没用:

  • 如果记录已经存在,那么您只是用当前值覆盖id
  • 如果记录重复,那么您在新记录中设置重复ID

相反,当您知道记录重复时,请根据您为表格定义的策略设置唯一ID:

OLA_ASSESSMENT_DTL OAD = db.OLA_ASSESSMENT_DTL.SingleOrDefault(
       ev => ev.OAD_RIV_ID == id);

transaction = "Modify"; // resetting the value of the variable
if (OAD == null)
{
    transaction = "Add";
    OAD = new OLA_ASSESSMENT_DTL();
    // TODO: Assign a unique id, or let the database assign one if the column is auto-increment
}