locked
Loading related data with POCOs RRS feed

  • Question

  • hi

     

    Navigation properties that return collections are of type EntityCollection. EntityCollection type also enables us to load related data explicitly by calling EntityCollection.Load.

    I'm using a POCO entity class of type Employee:

     

    public class Employee
    {
          private EntityCollection<Address> _addresses = new EntityCollection<Address>();
    
          public EntityCollection<Address>  Addresses
          {
              get { return _addresses; }
              set { _addresses = value; }
           }
    }
    

    Since Employee.Address navigation property is of type EntityCollection<Address>,  I assumed that I would be able to explicitly load related data simply by calling firstEmployee.Addresses.Load(), but instead I get "InvalidOperationException: Requested operation is not allowed when the owner of this RelatedEnd is null":

    Employee firstEmployee = ...
    firstEmployee.Addresses.Load(); // Exception
    


    I'm aware that we can instead call ObjectContext.LoadProperty<T>, but I'm still curious why when using POCO entities we can't load related data via EntityCollection.Load ( thus by calling Employee.Addresses.Load )?

     

    Thank you

    Tuesday, October 25, 2011 7:04 PM

All replies

  • Hi,

    Try to refer this link: http://msdn.microsoft.com/en-us/library/bb896376.aspx

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, October 31, 2011 7:19 AM
  • It turns out that if POCO navigation property is of type EntityCollection<Address>, then whenever we try to access this property, we get

    System.Data.EntityException: Unable to set field/property Addresses on entity type System.Data.Entity.DynamicProxies.Employee_DC24638F79D33E64DBB9038F9079C5E63190DE6C3B8EC3B0C7298A852023ED9E. See InnerException for details. ---> System.InvalidOperationException: The object could not be added to theEntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object.


    I must have been sleeping when creating this thread, since I have no idea how I've managed in my initial post to get a completely different exception ( InvalidOperationException ). I apologize for any inconveniences. 


    Anyways, in case someone will still be reading this thread, any ideas why accessing POCO navigation property of type EntityCollection<Address> throws an exception? 

    • Edited by KlemS100 Monday, October 31, 2011 7:14 PM
    Monday, October 31, 2011 7:12 PM