开发者

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 = resourceLanguageRe开发者_高级运维positoty.GetAllByResourceId(resource.Id);
    resource.ResourceLanguages = resourceLanguages;
}

Can anyone help me to sort this out?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜