Question

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.

Was it helpful?

Solution

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!");

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top