我收到以下代码的警告:主键错误。我看不出为什么会这样,我需要对其进行梳理。有人可以帮忙吗?
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:好的,当我打开标识插入时,更新成功,但是我不希望在此表上插入标识,因为从WebService传递了ID,所以我需要保留这些ID。
最佳答案
我不确定,因为我不太喜欢实体框架,但是您需要这一行吗?
theEvent.Event_ID = matchEvent.Event_ID;
它只是在之后
//There is an event with this ID, so check its last updated flag
if (theEvent.Last_Updated < matchEvent.Last_Updated)
而且我认为这是多余的,并且还可能导致主键错误,因为我认为一旦创建主键便无法将其分配给它。
更新资料
快速搜索,一旦创建了主键便无法更新,因此我很确定这是您的错误所在。
看到这样的答案:Update primary key value using entity framework
关于c# - Entity Framework 更新错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4158731/