开发者

Entity Framework Update and Insert Issue-ASP.NET MVC

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 d开发者_运维问答oes not get saved. shouldnt the following work?

public void SaveChanges(Project project, int ParentId)


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


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)

  • http://geekswithblogs.net/michelotti/archive/2007/12/25/117984.aspx
  • http://omaralzabir.com/linq_to_sql__how_to_attach_object_to_a_different_data_context/
  • http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/6f42d725-4540-4044-be86-afc7bc2d2b46/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜