0

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.

Filippo Vigani
  • 904
  • 1
  • 9
  • 22
  • What exactly are you going to do with that `List`? Can't some covariant interface (like `IEnumerable`, `IReadOnlyList`) work for you? – Ivan Stoev Aug 19 '16 at 16:28
  • Now I understood your problem. Is it possible to cast your `List` to `List` before passing it to dragInfo? I suspect you somehow have to store supply the dragInfo with something (your List), so it can be passed back in `dropInfo.Data` when you drag and drop, so you could cast it before. – Alisson Reinaldo Silva Aug 19 '16 at 16:51

2 Answers2

1

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.

eocron
  • 6,885
  • 1
  • 21
  • 50
  • While this would look like something that fits my case, unfortunately casting to List won't work, while casting to the non-generic List will, for some reason. – Filippo Vigani Aug 22 '16 at 08:17
0

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.

BRogers
  • 3,534
  • 4
  • 23
  • 32