Entity Framework - refresh objects from database

Nebojsa Veron picture Nebojsa Veron · Apr 2, 2010 · Viewed 27k times · Source

I'm having trouble with refreshing objects in my database. I have an two PC's and two applications.

On the first PC, there's an application which communicates with my database and adds some data to Measurements table. On my other PC, there's an application which retrives the latest Measurement under a timer, so it should retrive measurements added by the application on my first PC too.

The problem is it doesn't. On my application start, it caches all the data from database and never get new data added. I use Refresh() method which works well when I change any of the cached data, but it doesn't refresh newly added data.

Here is my method which should update the data:

    public static Entities myEntities = new Entities();

    public static Measurement GetLastMeasurement(int conditionId)
    {
        myEntities.Refresh(RefreshMode.StoreWins, myEntities.Measurements);

        return (from measurement in myEntities.Measurements
                where measurement.ConditionId == conditionId
                select measurement).OrderByDescending(cd => cd.Timestamp).First();
    }

P.S. Applications have different connection strings in app.config (different accounts for the same DB).

Answer

LukLed picture LukLed · Apr 2, 2010

This should work:

public static Entities myEntities = new Entities();

public static Measurement GetLastMeasurement(int conditionId)
{
    myEntities.Refresh(RefreshMode.StoreWins, myEntities.Measurements);
    var allMeasurements = myEntities.Measurements.ToList();//retrieves all measurements from database

    return (from measurement in allMeasurements
            where measurement.ConditionId == conditionId
            select measurement).OrderByDescending(cd => cd.Timestamp).First();
}

What sense makes caching when you refresh store every time you want to use it? You could chage it to:

public Measurement GetLastMeasurement(int conditionId)
{
    var entities = new Entities();
    return (from measurement in entities.Measurements
            where measurement.ConditionId == conditionId
            select measurement).OrderByDescending(cd => cd.Timestamp).First();
}

It also look up in database with every call, but makes much less operations.