Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting error "The property X on type Y cannot be set because the collection is already set to an EntityCollection"?

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?

like image 850
Febin J S Avatar asked Nov 28 '25 01:11

Febin J S


1 Answers

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.

like image 163
Ladislav Mrnka Avatar answered Dec 02 '25 03:12

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!