我收到以下代码的主键错误声明。我不明白为什么这可能是,我需要整理出来。任何人都可以用一双新鲜的眼睛帮忙吗?实体框架更新错误
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