0

I have the following:


public void SaveChanges(Project project, int ParentId)
        {
//If not updating then insert
if (!UpdateMode)
            {
                //Insert New Project Else Simply Save Context Changes
                this.Context.Projects.Add(project);    
            }
//save all changes
            this.Context.SaveChanges();
}

The idea is that if I am in insert mode add a new project else I am in update mode and I need to simply save all of the changes. My project that gets passed in has the changes that were made in the web page but it does not get saved. shouldnt the following work?

public void SaveChanges(Project project, int ParentId)

2
  • how do you know its in updatemode? Commented Jun 21, 2011 at 17:08
  • You need to add a lot more information. For example you haven't said what is wrong. What happens when you run the above? Commented Jun 21, 2011 at 17:12

2 Answers 2

1

The project coming in from the posted form is not attached to your object context. You need to attach it to the context.

public void SaveChanges(Project project, int ParentId)        {
    //If not updating then insert
    if (!UpdateMode)            {                
        //Insert New Project Else Simply Save Context Changes                
        this.Context.Projects.Add(project);                
    } else {
        this.Context.Attach(project);
        this.Context.ObjectStateManager.ChangeObjectState(project, EntityState.Modified);
    }
    //save all changes            
    this.Context.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

2 Comments

What is the syntax for 4.1? ObjectStateManager does not seem to exist.
Found it: this.Context.Entry(project).State = System.Data.EntityState.Modified;
0

Your Project object (if its an update instead of an insert) MUST be loaded from the same Data Context Object that you are calling SaveChanges on. If you load Project from a context in one library, and pass the Project around, then your update will fail. This is one of the stickier parts of EF/Linq-To-Sql.

Look into the "Attach" method to attach an existing entity to a different data context, but be warned, there's no magic bullet as far as I can tell. (Still looking for it myself)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.