2012-04-26 68 views
1

我编写的服务可以达到每周最新汇率的值。
但是,当我将值发送到数据库时出现错误。我在实体框架中创建了一个数据库模型。关联的数据库表名称为CURRENCYWEEKLY_VALUEAsp.net实体框架插入重复PK异常

相关栏目有KOD字段在CURRENCYKOD字段在WEEKLY_VALUE表中。 KOD字段WEEKLY_VALUE是Foreing_key。

我在这段代码中得到一个错误:

public void insertWeeklyCurrency(List<CURRENCY> currencyList) 
    { 
     myEntity = new CurrencyEntities(); 
     DateTime date = new DateTime(); 
     date = System.DateTime.Now; 
     String day= date.DayOfWeek.ToString(); 
     if (!day.Equals("Sunday") && !day.Equals("Saturday")) 
     { 
      WEEKLY_VALUE weeklyCurrency; 
      for (int i = 0; i < currencyList.Count; i++) 
      { 
       weeklyCurrency = new WEEKLY_VALUE(); 
       weeklyCurrency.KOD = currencyList[i].KOD; 
       weeklyCurrency.TARIH = currencyList[i].TARIH; 
       weeklyCurrency.DEGER = currencyList[i].F_SATIS; 
       weeklyCurrency.CURRENCYReference.Value=currencyList[i]; 
       myEntity.AddToWEEKLY_VALUE(weeklyCurrency); 
       myEntity.SaveChanges(); 
      } 
     } 
    } 

错误消息:

{“PRIMARY KEY约束 'PK_CURRENCY' 违反不能在对象插入重复键“dbo.CURRENCY '。\ r \ n声明已被终止。“}

如何处理这个错误?

回答

0

当你得到这个错误时,你很可能试图插入已经在表中的东西。

除了显而易见的,我需要查看模式以查明问题的确切位置。然而,

weeklyCurrency.CURRENCYReference.Value = currencyList [i];

看起来很可疑。如果KOD已经是货币的外键,那么这个CURRENCYReference值是什么?

+1

'CURRENCYReference'是在使用派生自“EntityObject”(而不是POCO)的实体时由EF生成的属性。每个参考导航属性'XYZ'具有'EntityReference '类型的相关'XYZReference'属性。这是“正常”,但有点老式的EF。 – Slauma 2012-04-26 16:32:05

+0

谢谢,我不知道。 – AwDogsGo2Heaven 2012-04-26 16:52:51

1

您需要在currencyList元素附加到上下文,让EF知道他们在数据库中已经存在,否则EF会尝试将它们插入到数据库:

for (int i = 0; i < currencyList.Count; i++) 
{ 
    myEntity.Currencies.Attach(currencyList[i]); 
    // etc. 
}