I am trying to implement an UnitOfWork type pattern where one DataContext is used over a short group of related methods and only at the end do I save the changes. However, I have found that entities added to the ObjectContext do seem to be available for reselection unless I SaveChanges, which is what I am trying to avoid. Can someone tell me if this is the expected behaviour? I have provided a psuedo test to illustrate:
[Test]
public void ObjectContext_ShouldSelectBackUncommitedValuesWhenUsingTheSameContext()
{
//arrange
var entityConnectionString = "MyEntityConnectionString";
var dataContext = new MyObjectContext(entityConnectionString);
var personCount = dataContext.People.AsQueryable<Person>().Count();
var person = new Person() { Name = "Bob" };
//act
dataContext.AddToPeople(person);
//assert
var actualPerson = dataContext.People.AsQueryable<Person>().Where(p => p.Name == "Bob").FirstOrDefault();
Assert.IsTrue(actualPerson != null,"Uncommitted Person should return when using same context");
var actualCount = dataContext.People.AsQueryable<Person>().Count();
Assert.IsTrue(actualCount == personCount + 1, String.Format("Expected {0} people but got {1} people", personCount + 1, actualCount));
//leave transaction to rollback
}
This test fails with the actualPerson being null and the Count of the People set not incrementing. Forgive me if there are any typos as I have just simplified my own ObjectContext.
FYI I am using EF 4.
TIA.
--EDIT-- Further by way of analogy, I was hoping to be able to work with uncommitted objects as I can in SQL eg:
CREATE TABLE Person (Name nvarchar(10));
INSERT INTO Person VALUES ('Francois')
INSERT INTO Person VALUES ('Hans')
SELECT COUNT(*) FROM Person
BEGIN TRANSACTION
INSERT INTO Person VALUES ('Bob')
SELECT 'Bob Lives!' WHERE EXISTS(SELECT * FROM Person WHERE NAME='Bob')
ROLLBACK TRANSACTION
DROP TABLE Person