none
Refresh DbContext doesn't work for relationships RRS feed

  • Question

  • Hi!

    I have a problem with refreshing the database-context to get all the changes made in the database.

    Here is my test-scenario:

    ParentTable    1 ------- n     ChildTable with ParentTableID (not an SQL-foreign-key)


    I use ADO.net to dynamically insert an entry in the ChildTable.
    After that, I reload the dbContext.
    When I use LINQ2Sql to grab all the Child-Entities belonging to a specific ParentTableEntry (pe1), I get different results when I perform these queries:

    int
     countViaRelationship = _pe1.Children.Count(); //i.e. 2
    
    int
     countViaSelectWithIdMatch = _dbContext.Children.Count(ch => ch.ParentTableID == pe1.ParentTableID); //i.e. 3
    
    
    

    As you can see from my comments, the Refresh()-Method of the datacontext doesn't update the relationship from the parent-entity to its corresponding children-entities.
    I'd be happy, if anyone can provide a solution other than re-instanciate the dbContext (which works fine though)

    Regards,
    Florian
    Thursday, March 18, 2010 10:32 AM

Answers

All replies

  • Hello,

    Refresh method will only refresh the current entities loaded in the DataContext.  Since the data is inserted outside the current DataContext, Refresh won't load them. 

    LINQ to SQL will cache the entities to improve the performance.  You can consider using the method in this thread to clear the cache and query the database again, http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/022d72e2-92a1-4645-af1a-59dbcfd85fff.  However, I recommend you create a new DataContext to make it easier if no other impact will be brought in. 


    Best Regards,
    Lingzhi Sun


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, March 25, 2010 9:09 AM
    Moderator
  • Hi Lingzhi:

    Sorry for asking this outside the EF forum, but is this true also for the ObjectContext? I mean, the refresh method in the Object Context will only refresh the loaded entities?

    I have a case where a user-roles (many to many relationship) doesn't get updated when I refresh the ObjectContext even if I user MergeOption.OverwriteChanges. The user data gets updated, but the roles he has don't.

    Thanks.

    Tuesday, October 5, 2010 4:47 PM