views:

48

answers:

2
+2  Q: 

Repository Pattern

Hello,

I've got a quick question regarding the use of repositories. But the best way to ask is to show a bit of pseudocode and you guys tell me what the result should be

  • Get a record from the repository with ID of 1 (assume it exists)

  • Edit a couple of properties

  • Query the repository again for an item with ID of 1

  • Result = ??

Should I get the object with updated values or the object without (original state), bearing in mind that since updating the values of properties (step 2) I have not told the repository to update this record.

I think I should get a copy of the original item and not a reference to the edited version.

Please tell me what is correct.

Cheers

A: 

Judging from your past questions I'm assuming you are using LINQ/C#?

If you are using a DataContext and you haven't called SubmitChanges() then you should get back the original unchanged object.

Just tested it. I was wrong, you get back the changed object.
If you set ObjectTrackingEnabled = false on the DataContext you will get the unchanged object.

jwsample
hey, good guess. I'm using Entity Framework code first, but whilst designing a TestDataContext (stores entities in memory) it actually got me thinking about the required behaviour.
nick
+1  A: 

The repository pattern is suppose to act like a collection of your objects, so ideally I think it should return the same object instance which would have the updates in it.

Generally there is an identity map somewhere so your repositories can keep track of what has already been loaded. With an identity map, when you fetch an object with the same Id you should always get the already loaded object back regardless of how many times. This is how all more sophisticated ORMs work and is generally a good practice. An identity map helps keep things in sync while you are in the same transaction and saves you some data access.

NHibernate's session has an identity map it keeps track of so you don't have to worry about trying to implement your own in your repositories. Also I believe you can use NHibernate's stateless session if you want to load another instance without change tracking, but I'm not positive on that.

Sean Copenhaver
Makes sense but initially counter intuitive for those of us used to doing things the old fashion way. I guess accidentally using a static DataContext is a good way to end up with some crazy data in your app.
jwsample