views:

148

answers:

1

Hey Folks,

I've got a slight problem when using a generic repository with EF4. First let me show you the code I use to access a collection of objects (this is code in the generic reposiroy):

 public IEnumerable<T> FindAll<T>() where T : class
    {
        return ObjectContext.CreateObjectSet<T>();
    }

Below is an example of this code being invoked for a repository of type Book

_returnedBooks = _dataContext.FindAll<Book>()
            .Where(b => b.Title == _editedtitle && b.Description == _editedDescription && b.ImageUrl == _editedImageUrl);

The code above shows me querying the data context for a book that has the properties that match values I used to edited a book previously (hence the _edited prefix). But once I'd edited this book, I did not call Save Changes on the data context.

And there is the problem, even though I haven't saved changes, the FindAll (in this case book) returns the book with edited values. However, when I inspect the DbSet (required to register the class for use with Code First), it is not in that collection.

So, I've not managed to track down any documentation for this behaviour, or whether I myself and missing the obvious.

Help meeeeeeeeeeeeeeeeeeeeeeeee :)

+1  A: 

Are you using the same DataContext? The DataContext caches the uncommitted changes and returns them on subsequent queries, regardless of if you've called SaveChanges() or not. If you wanted to avoid retrieving the uncommitted edits, you'd need to new a new or alternate context.

RobS
Hey RobS,I am using it in Singleton scope as defined my DI Container. However, I've also tried transient and request scope for both the data context and the repository factory that uses them with the same results.Probably best I double check this now. Thanks for taking the time to reply.
nick
Hey, I went back and realised that it was actually my tests that were saying the object had been updated - not my actual code. And in my tests......I was using the same DataContext instance - and, as you say, it was data caching.So, I prefixed each call to FindAll<T> with _dataContext = new NTCodingDataContext();. And my tests went green. Yeh baby!Sorry I can't mark as answer because I have a low reputation, but I'm definitely grateful you helped me :)
nick