开发者

Entity Framework reverting changes

I am develloping a web form that has a wizard with 4 steps:

On each step I'me creating new entities generated from a database.

The problem is that being a wizzard, the user can change the properties of the controls that will originate the values to be stored.

So I need to release the created entity objects or return that entity values to the original rows stored on the database.

How can I do this.

Should'n it work if I set each created entity object to null?

By the way this is how I'm doing it:

entities = new Entities();

...

Client client = new Client();
client.name = tbxName.text

...

entities.SaveC开发者_Python百科hanges();
entities.Connection.Close();   

So If this code is executed on the 2nd wizard part of a wizard of 3 parts and I go back and fowrward through this set more the once the client creating runs more than once, so there's my problem.

So how can I unCreate it :-P

Thannks!!!


If you are building wizard you must manage it as single operation. It means that you have to store built entity graph in the session and save it only if whole wizard is completed and confirmed. Your step logic also must check if related data are already present in the entity graph and use them instead of creating new one.


If your using Entity Framework, why not implement the Unit Of Work pattern? Each part of your wizard builds the UoW and the "final step" commits the unit of work.

There was an article called "The Unit Of Work Pattern And Persistence Ignorance" in MSDN magazine a few years ago that explains the concept.


This is the way I do it:

1- Create a place where you can manage your Session variables :

public class SessionObjects { }

2- I save my ObjectContext in the Session so I create a property to manage it in the mentioned class :

public static ObjectContextEntities ObjectContextEntities
{
    get
    {
        return (ObjectContextEntities)HttpContext.Current.Session["ObjectContextEntities"];
    }
    set
    {
        HttpContext.Current.Session["ObjectContextEntities"] = value;
    }

}

3- Initialize the ObjectContext on the wizard's start and dispose it on its end:

void StartWizard()
{
    SessionObject.ObjectContextEntities = new ObjectContextEntities(); 
}

void StartWizard()
{
    SessionObject.ObjectContextEntities = new ObjectContextEntities(); 
}

void EndWizard()
{
    ((ObjectContextEntities)SessionObject.ObjectContextEntities).Dispose();
}

4- To save wizard result to the database you can call:

void SaveWizard()
{
    ((ObjectContextEntities)SessionObject.ObjectContextEntities).SaveAllChanges();
}

5- To reset wizard simply call EndWizard then StartWizard .

I guess you know how to manage your ObjectEntity objects and in the ObjectContext so you can continue from here by your self ..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜