0

I have the following piece of code

private void DoAddPropertyType()
{
    var ctx = Globals.DbContext;
    var propType = new PropertyType()
    {
        ID = Guid.NewGuid(),
        Name = "NewType",
        Description = "New Property Type",
        ModifiedDate = DateTime.Now
    };
    ctx.AddToPropertyTypes(propType);
    PropertyTypes.Add(propType);
}

Globals.DbContext provides a static reference to the objectcontext initiated on startup. For some reason the ctx.AddToPropertyTypes(propType); bit does not add the entity to the context. If I breakpoint after that line and browse the ctx.PropertyTypes entity set it is not there. Any ideas?

EDIT 1: If I add a ctx.SaveChanges() after the ctx.AddToPropertyTypes(propType) and step the actual adding appears to happen only once SaveChanges execute. This however does not suit my requirements as I want to first validate objects prior to saving and wanted to iterate through the entities in the entity set. Does any one know of an alternative approach?

2
  • Where do you call SaveChanges? Commented Feb 26, 2013 at 10:31
  • Only later after doing some validation. See Edit 1 above Commented Feb 26, 2013 at 10:41

1 Answer 1

1

So that is the point of your issue. ctx.PropertyTypes is not a real collection - it is entrance to the database and your "browsing" actually executes query to the database where your new object was not yet stored. If you want to find a new object added to the context without saving it first you must search the object inside the ObjectStateManager:

var entity = ctx.ObjectStateManager
                .GetObjectStateEntries(EntityState.Added)
                .Where(e => !e.IsRelationship)
                .Select(e => e.Entity)
                .OfType<PropertyType>()
                .SingleOrDefault(p => p.ID == ...);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I think I understand EF a bit better now. You also showed me a way to get a list of all newly added entities which is helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.