I’m trying to figure out why this isn’t working…
DomainModel
public class ModelEntities : DbContext
{
public DbSet<Address> Addresses { get; set; }
}
Controller
public ViewResult List(int id)
{
var db = new ModelEntities();
var addresses = db.Addresses.Where(x => x.CustomerID == id).AsEnumerable();
return View(entities.Cast<AddressVM>());
}
View
@model IEnumerable<WebUI.Models.AddressVM>
...
AddressVM
public class AddressVM
{
public AddressVM(Address address) { Bind(address); }
private void Bind(Address address)
{
// Mapping logic is defined here
}
public static explicit operator AddressVM(Address address)
{
return new AddressVM(address);
}
}
Now, if I change the view to accept IEnumerable<DomainModel.Models.Address> and don’t do the cast everything works as expected.
When I try and do the cast I get the following error:
Unable to cast object of type ‘System.Data.Entity.DynamicProxies.Address_37444C79F0AB1E0A599C8797F37448F12213C5BCAC0611B4C1C8EFADDEFAA82C’ to type ‘WebUI.Models.AddressVM’.
In the controller, why is addresses a collection of dynamic proxies even after calling AsEnumerable()? What do I have to do to get a collection of my domain model objects so that I can cast them to the view model?
I bet your misunderstanding the concept of cast. A cast means the AddressVM instance is an Address instance… which i assume it’s not. You will probably have to “convert” or instantiate the AddressVM object from the Address object. try this :
[edit] According Brian’s answer, you can cast an object if there is an implicit conversion between your actual type and the target type.