views:

41

answers:

2

Having a EF Context and a Testenity I want to get the following test to work.

TestEntity testEntity = new TestEntity() { Name = "Hello World" };
context.TestEntities.AddObject(testEntity);
// missing Code
Assert.AreEqual(1, context.TestEntities.Count(), "Entity not in context!");

I know that it works with SaveChanges() but I do not want to save the Entity to the datasource.

+3  A: 
TestEntity testEntity = new TestEntity() { Name = "Hello World" };
context.TestEntities.AddObject(testEntity);

var entitiesInOSM = context.ObjectStateManager.
        GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged).
        Where(ent => ent.Entity is TestEntity).
        Select(ent => ent.Entity as TestEntity);

Assert.AreEqual(1, entitiesInOSM.Count(), "Entity not in context!");
Yakimych
this works. but doesn't look nice. isn't there a way to get a LINQ query against the context without saving?from TestEntity t in context.TestEntities ....
HumerGu
No. Whenever you execute a query against the context the underlying provider gets queried. That you don't want in your case.
Yakimych
A: 

What are you trying to achieve with your test? All this test would achieve here is to Assert the underlying Entity Framework ContextObject which is a pointless test for you.

If you're trying to then run additional tests for which the ObjectContext is a dependency you can mock out the ObjectContext with an interface. We create our own custom IObjectContext interface we extract from the T4 generated ContextObject off our model.

Daz Lewis
ok it is not really a test case. what i want to achieve is to add entities to the context and not to save them to the database but query the context for added entities before saving!!
HumerGu