Renier
Renier

Reputation: 540

Entity Framework AddObject not adding Object to EntitySet

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?

Upvotes: 0

Views: 939

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

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 == ...);

Upvotes: 1

Related Questions