I think I'm missing something ver开发者_StackOverflow社区y simple here.
I have an EF4 ObjectContext that contains an ObjectSet of type Thing, which is mapped to a table in my database called Things. If I add a Thing to the Things ObjectSet, that Thing is not visible in Things until I call SaveChanges() on the ObjectContext.
So, in the following test fixture, AddToThings_AddsItemsToContext_WithSaveChanges passes but AddToThings_AddsItemsToContext_WithoutSaveChanges fails:
[TestFixture]
public class Ef4Tests
{
[SetUp]
public void SetUp()
{
var ef4PocEntities = new Ef4PocEntities();
ef4PocEntities.DeleteDatabase();
ef4PocEntities.CreateDatabase();
}
// this test passes
[Test]
public void AddToThings_AddsItemsToContext_WithSaveChanges()
{
var ef4PocEntities = new Ef4PocEntities();
Assert.AreEqual(0, ef4PocEntities.Things.Count());
ef4PocEntities.AddToThings(new Thing {Name = "Bob"});
ef4PocEntities.SaveChanges();
Assert.AreEqual(1, ef4PocEntities.Things.Count());
}
// this test fails
[Test]
public void AddToThings_AddsItemsToContext_WithoutSaveChanges()
{
var ef4PocEntities = new Ef4PocEntities();
Assert.AreEqual(0, ef4PocEntities.Things.Count());
ef4PocEntities.AddToThings(new Thing {Name = "Bob"});
Assert.AreEqual(1, ef4PocEntities.Things.Count());
}
}
Is there a way to do what I want? I.e. add Entities to an ObjectSet and have them visible without saving to the database?
The answer is here: Finding Entity Framework contexts.
精彩评论