views:

344

answers:

1

I'm struggling with the Entity Framework when creating a new record in a one to many relation. I've the following tables defined:

Person
PersonInternetAddresses
InternetAddresses

The Entity Framework has created the EntityObjects Person with a navigation property named PersonInternetAddresses and InternetAddresses with a navigation property to persons.

To create a new InternetAddresses record i've created a form with a couple of text fields and a bindingsource to InternetAddresses.

Under my "new" button i've placed the following code:

internetAddressesBindingSource.AddNew();            
(internetAddressesBindingSource.Current as InternetAddresses).Id = Guid.NewGuid();
(internetAddressesBindingSource.Current as InternetAddresses).Persons = InternetAddresses.Persons;

On the last line i'm getting the following error:

The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph.

I'm guessing that i cannot set the person through the navigation property of the InternetAddresses which would mean that the Entity Framework itself would create a PersonInternetAddresses record. Since there isn't a PersonsInternetAddresses EntityObject in the model i'm pretty stuck!

+1  A: 

Found it!

Persons is of type EntityCollection duh! For testing purposes i've changed the code to:

internetAddressesBindingSource.AddNew();            
        (internetAddressesBindingSource.Current as InternetAddresses).Id = Guid.NewGuid();            

        foreach(Person p in InternetAddresses.Persons)
        {
            (internetAddressesBindingSource.Current as InternetAddresses).Persons.Add(p);
        }
madC