EF4.1 POCO: Why should I use ICollection

為{幸葍}努か 提交于 2019-12-06 01:11:26

问题


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.:

Person Paul = TravelTicket.Members[3];

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.ICollection

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


回答1:


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.




回答2:


Just use ToList():

Person Paul = TravelTicket.Members.ToList()[3];

EF isn't going to query data until you actually try to access it - and a collection doesn't try until you iterate it, while ToList must instantiate each instance.

Even better, be more specific:

Person Paul = TravelTicket.Members.Where(m=>m.Id == 3);  // or some such similar filter

Then you only instance ONE Member - the one you want.

Note you may need Members.AsQueryable().Where instead - I never remember...




回答3:


ICollection implements IEnumerable, you should be able to get the item by index using Enumerable.ElementAt<TSource> method



来源:https://stackoverflow.com/questions/6439425/ef4-1-poco-why-should-i-use-icollection

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