为什么我得到错误“类型Y上的属性X无法设置,因为集合已设置为EntityCollection”? [英] Why am I getting error "The property X on type Y cannot be set because the collection is already set to an EntityCollection"?

查看:130
本文介绍了为什么我得到错误“类型Y上的属性X无法设置,因为集合已设置为EntityCollection”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在EF4中尝试将一个集合映射到另一个集合时,出现了这个错误。属性ResourceLanguages Resource_EF810770B4FCA2E071F38C2F2EE328AAC216CA2A7BF157503E6658A42D7CF53A'无法设置,因为集合已设置为EntityCollection。


我正在尝试像这样编码

  foreach(资源中的var资源)
{
resourceLanguages = resourceLanguageRepositoty.GetAllByResourceId(resource.Id);
resource.ResourceLanguages = resourceLanguages;
}

任何人都可以帮我排序吗?

解决方案

使用代理时,不能将集合分配给物化导航属性。你找到一个解决方案,但它看起来相当无效。首先,如果您的资源与上下文相关联,那么语言将在需要时通过延迟加载进行加载,但您也可以在单个查询中使用eager加载和加载其语言的所有资源:

  var resources = context.Resources.Include(ResourceLanguages)。ToList(); 

您的解决方案导致N + 1数据库查询,其中N是集合中的资源数。 p>

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?

解决方案

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.

这篇关于为什么我得到错误“类型Y上的属性X无法设置,因为集合已设置为EntityCollection”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆