Reputation: 1368
While I was trying to map a collection to another in EF4 I got this error.
The property 'ResourceLanguages' on type 'Resource_EF810770B4FCA2E071F38C2F2EE328AAC216CA2A7BF157503E6658A42D7CF53A' cannot be set because the collection is already set to an EntityCollection.
I was trying to code like this
foreach (var resource in resources)
{
resourceLanguages = resourceLanguageRepositoty.GetAllByResourceId(resource.Id);
resource.ResourceLanguages = resourceLanguages;
}
Can anyone help me to sort this out?
Upvotes: 3
Views: 2680
Reputation: 364259
You can't assign collection to materialized navigation property when using proxies. You find one solution but imho it looks quite ineffective. First if your resources are attached to context, languages will be loaded by lazy loading once they are needed but you can also use eager loading and load all resources with their languages in a single query:
var resources = context.Resources.Include("ResourceLanguages").ToList();
Your solution results in N+1 database queries where N is number of resources in the collection.
Upvotes: 3