开发者

caching problem in entity framework 4

I am using entity framework 4 to create entities from DB.

I have 2 entity contexts to connect to db. let's say c开发者_StackOverflowontext1 and context2

However, when I do the following steps, 1. get data from context1 2. get same data row from context2 3. update same data row to context1 4. get same data row from context2

context2 doesn't change after updating in step 3.

I guess context2 cached the data. not getting data from db everytime.

how to fix it?

Thanks~


The Entity Context get the data from the database only once then it have cached in memory.

To get the data from the Database, you have first to call SaveChanges() on Context1. Then, to call Refresh(RefreshMode.StoreWins, Context2.EntityToRefresh) to get the database values in the context2.

You can also use a Share/Static context to do your queries, in that you can be sure that you have the same data for all your queries.

You can implement it like this

public class SharedObjectContext
{
    private readonly WestwindEntities context;

    #region Singleton Pattern

    // Static members are lazily initialized.
    // .NET guarantees thread safety for static initialization.
    private static readonly SharedObjectContext instance = new SharedObjectContext();

    // Make the constructor private to hide it. 
    // This class adheres to the singleton pattern.
    private SharedObjectContext()
    {
        // Create the ObjectContext.
        context = new WestwindEntities();
    }

    // Return the single instance of the ClientSessionManager type.
    public static SharedObjectContext Instance
    {
        get
        {
            return instance;
        }
    }   

    #endregion

    public WestwindEntities Context
    {
        get
        {
            return context;
        }
    }
} 


You have to call SaveChanges() to, well, save the changes (back to the DB).

Furthermore, if you've already enumerated the collection from step 2, then you won't have the updates from step 3, even if you're saving changes back to the database.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜