Reputation: 1004
Scenario: I have a collection of entity framework entities using lazy loading and are therefor DynamicProxies
. Then there is a a method that passes some selected items to an override I'm writing as object
. I need to convert the List<DynamicProxies.EntityABCD>
(which is actually passed as object
) to a List<Entity>
.
However casting the list this way
dropInfo.Data as List<MyEntity>
will return null. I can't even use the generic method Cast<T>
because again the source list is passed as an object
.
I also tried
dropInfo.Data as List<object>
but it still will return null.
Thanks in advance
EDIT: Managed to get a cleaner list with
((IList)dropInfo.Data).Cast<MyEntity>()
However I still need to check for errors etc.
Upvotes: 0
Views: 2887
Reputation: 3614
I know it's been awhile since this was asked, but figured that this would save someone time.
You could just grab your entity and cast in a single operation assuming there's a direct cast available:
var data = datasource.Where(x => x.id == myID).Cast<MyEntity>().ToList();
data
will now be typed as a List<MyEntity>
and you should be good to go.
Upvotes: 0
Reputation: 7536
You can use dynamic quantifier for this, if you know your objects structure:
var result = ((List<dynamic>)dropInfo.Data).Select(ConvertToMyEntityMethod).ToList();
public static MyEntity ConvertToMyEntity(dynamic obj)
{
return new MyEntity(){ SomeIntProperty = (int)obj.SomeIntProperty };
}
Dynamic allow you to get access to class members through reflection without compilation errors. This is really bad solution for performance, but very good if you work with MVVM bindings.
Upvotes: 1