AddObject and CreateObjectSet RRS feed

  • Question

  • Hi all,

         I'm using Visual Studio 2010 and I have a problem with AddObject - CreateObjectSet.  I'm using a kind of POCO.  Here is a little code snippet:

    var container = new myContainer(); //inherit from ObjectContext

    var numRef = new NumeroReference(Type.Nas, "123456789"); //inherit from EntityObject

    container.AddObject("NumeroReferenceEntitySet", numRef);

    //The following LINQ is supposed to return my newly createobject, but it didn't, it returns null.  In fact, I add entities in a class and I use CreateObjectSet in another class, so I cannot use ObjectStateManager.GetObjectStateEntry.  The following line seems to always go in database, even if I do AcceptAllChanges or DetectChanges before.  I tried to do AddObject on this newly ObjectSet after, but I'm unable to retrieve my new object.

    var result = container.CreateObjectSet<NumeroReference>("NumeroReferenceEntitySet").FirstOrDefault(n => n.Type == Type.Nas);

     Any idea how to retrieve this entity from container?

    Thank you




    Tuesday, May 25, 2010 7:14 PM


  • Are you using the same myContainer instance to call AddObject and CreateObjectSet? It sounds like your use of CreateObjectSet<T> isn't quite right. Here are a few explanations that might help:

    ObjectSet<T> is really a representation of a set of entities in the database. You can conceptually think of an ObjectSet as a database table. Any LINQ query you perform against an ObjectSet<T> will perform a database query. An ObjectSet is not just a collection of entities that you can filter with LINQ to object queries.

    AddObject will put an entity into the ObjectContext. You can find this entity in the ObjectStateManager.GetObjectStateEntry of the ObjectContext instance where you added it (just look for EntityState.Added items).

    If you want to "query" just the local data that is stored in the myContainer ObjectContext's ObjectStateManager, you can do something like this:

    IEnumerable<T> LocalQuery(this ObjectContext ctx, string entitySet)


        return ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged | EntityState.Added | EntityState.Modified).Where(e => e.EntitySet != null && e.EntitySet.Name == entitySet);


    Then to do more filtering you could do this:

    var result = container.LocalQuery("NumeroReferenceEntitySet").FirstOrDefault(n => n.Type == Type.Nas);

    And it will only query the entities that are already stored in the container.


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Wednesday, May 26, 2010 5:12 AM