gpt4 book ai didi

c# - EF4.1 POCO : Why should I use ICollection

转载 作者:太空狗 更新时间:2023-10-29 21:10:35 26 4
gpt4 key购买 nike

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

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

但是,这会导致我的代码出现问题,我需要通过索引访问集合的成员,例如:

人保罗 = TravelTicket.Members[3];

无法将带 [] 的索引应用于类型为“System.Collections.Generic.ICollection”的表达式

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

最佳答案

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

关于c# - EF4.1 POCO : Why should I use ICollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6439425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com