Entity Framework - database object refresh

database entity-framework objectcontext wpf

Question

My database objects aren't refreshing properly. I have two programs and two PCs.

A program that connects to my database and updates the Measurements table is present on the first PC. It should get measures that were uploaded by the program on my first PC because it retrieves the most recent measurement under a timer on my second PC.

The issue is that it doesn't. My program starts up with a cache of all the database data and never receives any fresh data. When I modify any of the cached data, the Refresh() technique, which I use, works great, however it doesn't update freshly inserted data.

Here is how I think the data should be updated:

    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' app.config files include several connection strings (different accounts for the same DB).

1
10
6/5/2015 10:00:33 PM

Accepted Answer

This ought to 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 good is caching if you have to reload the store every time you need it? You may alter it such that:

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

Every time you call, it likewise searches the database, although it does many fewer actions.

9
4/2/2010 9:17:07 AM

Popular Answer

You may use the AsNoTracking() function on your entities as of EF 4.1.

return myEntities.Measurements.AsNoTracking();

Keep in mind that AsNoTracking() just returns the entities straight from your data store, not adding them to your context for tracking.

See http://blogs.msdn.com/b/adonet/archive/2011/02/05/using-dbcontext-in-ef-feature-ctp5-part-11-load-and-asnotracking.aspx for further information.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow