实体框架 - 从数据库刷新对象 [英] Entity Framework - refresh objects from database

查看:246
本文介绍了实体框架 - 从数据库刷新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中刷新对象时遇到问题。我有一个两个电脑和两个应用程序。

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.

问题是它不是。在我的应用程序启动时,它缓存数据库中的所有数据,并且不会添加新数据。我使用Refresh()方法,当我更改任何缓存的数据,但它不刷新新添加的数据工作。

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


应用程序在app.config中有不同的连接字符串(对于同一个数据库,不同的帐户)。

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

推荐答案

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.

这篇关于实体框架 - 从数据库刷新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆