开发者

EF4.1 POCO: Why should I use 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.:

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?


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.


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜