Refreshing Data Using Entity Framework

前端 未结 2 638
慢半拍i
慢半拍i 2020-12-06 02:41

I\'m trying to use Entity Framework to query database and I have following code that I\'m using to get some data.

var students= MyEntities.Students.Where(s =         


        
相关标签:
2条回答
  • 2020-12-06 02:54

    No it never worked. This is essential behavior of entity framework (and many ORM tools) called identity map (explanation here).

    If you run the query on the same context you will not get your entities updated. It will only append new entities created in the database between running those two queries. If you want to force EF to reload entities you must do something like this:

    ObjectQuery query = MyEntities.Students;
    query.MergeOption = MergeOption.OverwriteChanges;
    var students = query.Where(s => s.Age > 20).ToList();
    
    0 讨论(0)
  • 2020-12-06 03:13

    You are running into issues because EF caches data, so if the data changes behind the scenes, and you dont dispose/reopen your context you are going to run into issues.

    The general rule of thumb is to keep the lifetime of the context as short as possible, to circumvent issues like you just mentioned.

    Please do not disregard what I said above, but if you would like to force a refresh from the DB you could use the Refresh() method.

    0 讨论(0)
提交回复
热议问题