Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

In my project I am working with an SQL database and entity framework.
I am using the Unit of Work pattern to manage the different data sets and commit changes to it.
The object sets are created as follows:
C#
private IObjectSet<DataObject> dataObjects;
public IObjectSet<DataObject> DataObjects
{
    get
    {
        if (dataObjects == null)
        {
            dataObjects = context.CreateObjectSet<DataObject>();
        }
        return dataObjects;
     }
}

My question is related to the updating of the datasets that are contained in the Unit of Work. When first creating a data set, they are filled correctly with data from the database.

However, when any property of any of these data objects is changed from a different location, it is not updated in my Unit of Work. When I now try to execute a query on the (modified) object set, the result is based on the data from the database, even though the data set from my Unit of Work still contains the old (unmodified) data.

The correct object is retrieved from the query (as based on the database), while the data contained in the retrieved object (as based on the Unit of Work) is not.

By adding
C#
context.Refresh(RefreshMode.StoreWins, dataObjects);
to the ObjectSet, the correct value is retrieved, but I wonder if this is the best solution.

How is it possible that objects are correctly added and removed from the data set at runtime, but changes to the object's properties are not registered in the unit of work.

Thank you in advance.
Posted

1 solution

You should be disposing your context and recreating it every time it is called by your UnitOfWork. The context model will be cached, but the 2nd level cache will be cleared by that process.

For example:

C#
public class UnitOfWork
{
    public IObjectSet<dataobject> DataObjects
    {
        get
        {
            using(var context = new MyContext())
            {
                return context.CreateObjectSet<dataobject>();
            }
         }
    }
}
</dataobject></dataobject>


As you'll see people say all over, context instances are cheap. This also enforces the UoW patter properly, rather than letting your context bloat.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900