1

I have a entity class generated by entity framework.

Then I created my custom POCO class that is pretty much the same as entity class which i use as viewmodel for asp.net mvc application.

Is there a way to make entity class castable to POCO class?

I ask because I need something like this:

db.Accounts.Cast<ViewModels.AccountVM>()

instead of this:

db.Accounts.ToList<ViewModels.AccountVM>()

saving few database cycles.

Thanks for insight

Milos Mijatovic
  • 955
  • 1
  • 17
  • 34
  • Do you ever actually use the EF generated classes? – Jaime Feb 24 '12 at 20:58
  • 3
    Have you tried adding an explicit cast operator (http://msdn.microsoft.com/en-us/library/85w54y0a.aspx) to your POCO view model? I'm not entirely sure if it will work but it's worth a try. – sellmeadog Feb 24 '12 at 20:59
  • @Janime. Sure I use them. For persistence. But they are not good for my pages. – Milos Mijatovic Feb 24 '12 at 21:21
  • @crazyarabian. Good tip. I added explicit cast, and compiler doesn't mind, but ef does. I get a runtime error. It says it only supports casting to primitive datatypes. Thanks though. – Milos Mijatovic Feb 24 '12 at 21:40
  • if you use classes generated by the Entity Framework (that derive from EntityObject) you will not be able to use your POCO classes with your context. The reason for this is that ObjectContext maps the generated classes to the objects from concetpual model and if it sees a type that it does not know about it will throw even if you are able to cast between the POCO an non-POCO types. Is there any reason why you don't use POCO classes with EF? This way you will only have one type and you would not have to cast... – Pawel Feb 24 '12 at 23:20
  • I looks like you confuse cast and convert. But I think you actually want neither. This is more like _mapping_: more or less similar properties of two different classes are copied to one another. A useful tool for that could be Automapper. – Gert Arnold Feb 25 '12 at 10:49
  • You can use reflection to loop all properties and fill out your new class list – Amen Ayach Feb 25 '12 at 11:06
  • @GertArnold. Yeah, i've stumbled upon that. I'd be happy if you could provide a link with some useful examples. I've been trying but no luck. Even a video i found doesn't work. – Milos Mijatovic Feb 25 '12 at 17:58
  • OK, I'm in a generous mood today: http://visualstudiomagazine.com/articles/2012/02/01/simplify-your-projections-with-automapper.aspx – Gert Arnold Feb 25 '12 at 19:54
  • This might be help http://stackoverflow.com/questions/3672742/cast-class-into-another-class-or-convert-class-to-another – William Ardila Sep 28 '16 at 16:48

0 Answers0