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

别来无恙 提交于 2020-01-04 02:49:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5619904/why-am-i-getting-error-the-property-x-on-type-y-cannot-be-set-because-the-colle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!