本文介绍了EF4.1 POCO:为什么要使用ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为Entity Framework 4.1集合创建的POCO类的几乎所有示例中,都是使用ICollection接口定义的:

In nearly all examples of POCO classes created for Entity Framework 4.1 collections are defined using the ICollection interface:

public class TravelTicket
{
    public virtual int Id { get; set; }
    public string Destination { get; set; }
    public virtual ICollection<Person> Members { get; set; }
}

但是,这在我的代码中引起了一个问题,我需要按索引访问集合的成员,例如:

However, this causes an issue in my code where I need to access a member of the collection by index, e.g.:

人员Paul = TravelTicket.Members [3];

Person Paul = TravelTicket.Members[3];

不能将[]的索引应用于类型为'System.Collections.Generic.ICollection

那么我该如何解决这个问题,我应该始终将ICollection用于我的POCO集合吗?

So how do I get round this problem and should I always use ICollection for my POCO collections?

推荐答案

这是因为一旦您将导航属性标记为虚拟,便会创建实体的代理,并且它将HashSet用作导航属性-哈希集不允许索引.通过索引访问相关实体似乎不是一种好方法,因为从数据库中检索实体并不能确保相关实体在集合中始终具有相同的索引.

It is because once you mark your navigation property virtual the proxy of your entity is created and it uses HashSet for navigation properties - hash set doesn't allow indexing. Accessing related entities by index doesn't seem like good approach because retrieving entity from database doesn't ensure that related entities will always have the same index in the collection.

这篇关于EF4.1 POCO:为什么要使用ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 03:09