Friday, February 6, 2009

When an EntityCollection isn't an IEnumerable...

I usually convert all my entity collections to plain old Arrays and I use the List.ToArray method to make the conversion. I push the data into a List via the constructor by casting the needed data to an IEnumerable.

This all goes well when I do a:
var data = (from iterEntity in Db.Table
select iterEntity);

I can do a:
var myList = new List((IEnumerable)data);
MyEntityType[] myArr = myList.ToArray();


However, when I select a set of related entities like so:
var data = (from iterOtherEntity in Db.OtherTable
where iterOtherEntity.refId = 911
select iterOtherEntity.MyEntities);

I can no longer cast data to an IEnumerable type, and so can't push data into a List via its constructor... I now have to write a foreach loop to do the same conversion to an array. :-(


UPDATE: There is an AsEnumerable extension method that you could try on the EntityCollection object (data). I didn't get a chance to try it yet, but I will as soon as I boot up in Windows again.

No comments: