我正在使用带有EF4的ASP.NET MVC2。我需要为我的两个类PersonP和AddressP创建POCO,它们对应于它们的EF4'复杂'类(包括导航属性和OnPropertyChanged()之类的东西)。仅将PersonP映射为单独工作,但PersonP包含AddressP(外键) - 如何使用IQueryable表达式映射它?
这是我尝试过的:
class AddressP
{
int Id { get; set; }
string Street { get; set; }
}
class PersonP
{
int Id { get; set; }
string FirstName { get; set; }
AddressP Address { get; set; }
}
IQueryable<PersonP> persons = _repo.QueryAll()
.Include("Address")
.Select(p => new PersonP
{
Id = p.Id,
FirstName = p.FirstName,
//Address = p.Address <-- I'd like to do this, but p.Address is Address, not AddressP
//Address = (p.Address == null) ? null :
//new AddressP <-- does not work; can't use CLR object in LINQ runtime expression
//{
// Id = p.Address.Id,
// Street = p.Address.Street
//}
});
没有.Include("Address")
我不会从地址表中检索任何内容这是正确的吗?
如何使用上面的Address
语句将AddressP
映射到PersonP
Select()
内?
谢谢。
答案 0 :(得分:1)
// First we execute the query:
IQueryable<PersonP> persons = _repo.QueryAll().Include("Address").ToList();
// Now we have a IEnumerable and we can safely do the mappings:
persons.Select(p => new PersonP
{
Id = p.Id,
FirstName = p.FirstName,
Address = (p.Address == null) ? null : new AddressP()
{
Id = p.Address.Id,
Street = p.Address.Street
}
}).ToList();
虽然这个解决方案可以解决问题,但如果打算使用POCO类,你一定要考虑利用EF4.0 POCO支持并直接使用POCO类和EF,而不是之后映射它们。一个好的开始就是这个演练:
Walkthrough: POCO Template for the Entity Framework