[英]Entity Framework Code First: How can I cast a set of entities returned from the database?
I'm trying to figure out why this isn't working... 我想弄清楚为什么这不起作用......
DomainModel 的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 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. 现在,如果我更改视图以接受IEnumerable<DomainModel.Models.Address>
并且不执行转换,则一切都按预期工作。
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'. 无法将类型为“System.Data.Entity.DynamicProxies.Address_37444C79F0AB1E0A599C8797F37448F12213C5BCAC0611B4C1C8EFADDEFAA82C”的对象强制转换为“WebUI.Models.AddressVM”。
In the controller, why is addresses
a collection of dynamic proxies even after calling AsEnumerable()
? 在控制器中,为什么即使在调用AsEnumerable()
之后也会addresses
动态代理的集合? 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. 强制转换意味着AddressVM实例是一个Address实例...我认为它不是。 You will probably have to "convert" or instantiate the AddressVM object from the Address object. 您可能必须从Address对象“转换”或实例化AddressVM对象。 try this : 试试这个 :
public ViewResult List(int id)
{
var db = new ModelEntities();
var addresses = from a in db.Addresses.Where(x => x.CustomerID == id)
select new AddressVM(a);
return View(addresses );
}
[edit] According Brian's answer , you can cast an object if there is an implicit conversion between your actual type and the target type. [编辑]根据Brian的回答 ,如果实际类型和目标类型之间存在隐式转换,则可以转换对象。
You need to setup an explicit operator on your AddressVM
if you want to be able to cast an Address
to it. 如果您希望能够为其转换Address
,则需要在AddressVM
上设置显式运算符 。 You might take a look at AutoMapper if you want to move data from a domain model to a view model fairly easily. 如果要将数据从域模型轻松移动到视图模型,可以查看AutoMapper。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.