new entity saved and added to context, but when retrieving it shortly after SaveChanges returns the "Entity" rather than DynamicProxy so some elements are null RRS feed

  • Question

  • Hopefully this is something easy to fix.

    Using CodeFirst/POCOs, EF 4.3.1 and dynamic proxies.

    I've got an Add routine that adds an order to the context the order has orderstatus

    everything works fine except for one bit where a newly added item, "Add(new Order{1, name, stuff...})" is added.

    Committed... again works fine and the order appears in the DB and that kind of thing.

    But then the next thing done is "view the details" and it opens back up the context and uses ".Find(id)" to get the order we just added and it comes back, but breaking on the offending line of code (which complains "object reference is not set to an instance of an object" by the way), I note that when you do this for an "older" order and it works, its returning a dynamic proxy (ie the object if you look in the VS IDE at the actual object it says "System.Data.Entity.DynamicProxies.Order_0D16425782ADB3D75999F74F5AB5D0FEAA5E2230358813B7625CF436CB43493A" rather than "MyProj.Entities.Order"...

    However in the "new item" case it seems to be looking at the element in the "local" (presumably cached/pre-loaded) items in the DbSet, but it contains a mixture of Proxy and "real" entities of the  type "Order"...

    I also note that if I dig deep enough into the dbContext and look at the "MyProjContext" DbSets, and have a look at the results of retrieving the data I have (for example) 12 "DynamicProxies..." and one "MyProj.Entities.Order" after adding a new entity.

    What have I done wrong, or what am I missing... do I need to forcibly discard and recreate the dbContext? is there something in "SaveChanges" that I'm not doing to get the "new Order()" to *become* a proxy, so that things like "OrderState.Name" are not failing because "OrderStateId" is set but "OrderState" (of the type "public virtual OrderState") is null...

    I'm wondering if I need to be using the DbContext/DbSet "Create" or "New" function to instantiate a new DynamicProxy#obj for my new entities before attaching/adding them... if this is the case can someone point me at the doco for this as I must have missed it...

    Little help?

    • Edited by noJedi Wednesday, July 25, 2012 5:46 AM
    Wednesday, July 25, 2012 3:13 AM