开发者

Entity Framework Update error

开发者 https://www.devze.com 2023-01-24 09:53 出处:网络
I am getting a voialation of Primary key error with the following code. I can\'t see for looking as to why this may be and I need to sort it out. Can anybody help with a fresh pair of eyes?

I am getting a voialation of Primary key error with the following code. I can't see for looking as to why this may be and I need to sort it out. Can anybody help with a fresh pair of eyes?

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();

UPDATE 1: The following is the error I get when SaveChanges() is called:

{"Violation of PRIMARY KEY constraint 'PK_Matches_1'. Cannot insert duplicate key in object 'dbo.Matches'.\r\nThe statement has been terminated."}

UPDATE 2: I am not using identity insert on the DB table for this as this is an import from a 3rd party Web Service where I need to retain all Ids. I am not sure if this will affect the update process with entity framework?

UPDATE 3: Ok well when I turn on identity insert the update is successful however I dont wish t开发者_运维问答o have indentity insert on this table as the Ids are passed in from a WebService and I need to retain these Ids.


I'm not sure, because I'm not too hot on Entity Framework, but do you need this line?

theEvent.Event_ID = matchEvent.Event_ID;

It comes just after

//There is an event with this ID, so check its last updated flag
if (theEvent.Last_Updated < matchEvent.Last_Updated)

and I would think it's redundant, and also might cause a Primary Key error, as I don't think you can assign to a primary key once it's been created.

Update

Did a quick search, and you can't update a primary key once it's been created, so I'm pretty sure this is where your error is.

See this SO answer: Update primary key value using entity framework


I believe that your problem lies when you are updating the Event_ID property. The object you requested from your database through the match DBContext already contains that same Event_ID as the Web service. Therefore, there is no need to update this value

if (theEvent.Last_Updated < matchEvent.Last_Updated) 
{
  //Update the current event
  theEvent.Event_ID = matchEvent.Event_ID;  // <-- Delete this line.
  ...
}

You may ask, why it matters since both values are the same? As it so happens the DBContext keeps track of your objects and its changes. In the context itself, each property has an original and current value. When you assigned the same value to the Event_ID the context is going to interpret it as a compleately different value even though is the same.

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消