我收到以下代碼的主鍵錯誤聲明。我不明白爲什麼這可能是,我需要整理出來。任何人都可以用一雙新鮮的眼睛幫忙嗎?實體框架更新錯誤
var events = (from e in nodes.Descendants("event")
select new Event
{
Event_ID = int.Parse(e.Attribute("event_id").Value),
Name = e.Attribute("name").Value,
Code = e.Attribute("code").Value,
Minute = e.Attribute("minute").Value != String.Empty ? int.Parse(e.Attribute("minute").Value) : 0,
Minute_Extra = e.Attribute("minute_extra").Value != String.Empty ? int.Parse(e.Attribute("minute_extra").Value) : 0,
Team = GetTeam(e.Attribute("team_id")),
Last_Updated = DateTime.Parse((FormatDateTime(e.Attribute("last_updated").Value)))
});
foreach (Event matchEvent in events)
{
//Check to see if this event exists
if (match.Events.Any(o => o.Event_ID == matchEvent.Event_ID))
{
Event theEvent = (from m in match.Events
where m.Event_ID == matchEvent.Event_ID
select m).FirstOrDefault();
//There is an event with this ID, so check its last updated flag
if (theEvent.Last_Updated < matchEvent.Last_Updated)
{
//Update the current event
theEvent.Event_ID = matchEvent.Event_ID;
theEvent.Name = matchEvent.Name;
theEvent.Code = matchEvent.Code;
theEvent.Minute = matchEvent.Minute;
theEvent.Minute_Extra = matchEvent.Minute_Extra;
theEvent.Team = matchEvent.Team;
theEvent.Last_Updated = matchEvent.Last_Updated;
}
}
//If the event is not there we need to add it
else
{
match.Events.Add(matchEvent);
}
myDb.SaveChanges();
更新1:以下是錯誤我得到的時候調用SaveChanges()被調用:
{"Violation of PRIMARY KEY constraint 'PK_Matches_1'. Cannot insert duplicate key in object 'dbo.Matches'.\r\nThe statement has been terminated."}
更新2:我不使用的數據庫表標識插入這個,因爲這是從第三方Web服務導入的,我需要保留所有Id。我不確定這是否會影響實體框架的更新過程?
更新3:好吧,當我打開身份插入更新成功,但是我不希望在該表上插入indentity,因爲Ids是從WebService傳入的,我需要保留這些ID。
哪一行是錯誤?錯誤信息中是否有任何可能有用的信息? – 2010-11-11 21:16:20
你忘了將PK屬性標記爲「自動生成」並不是那麼簡單? – Ozzy 2010-11-11 21:33:18
在這種情況下PK不是自動生成的,也許這是我的問題?這基本上是從已經指定了ID的第三方Web服務運行導入? – Kevin 2010-11-11 22:29:40