IQueryable 实体框架 POCO 映射
我正在使用 ASP.NET MVC2 和 EF4。我需要为我的两个类 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")
我不会从地址表中检索任何内容,这是正确的吗?如何使用上面的
Select()
语句将Address
映射到PersonP
内的AddressP
?< /p>
谢谢。
I am using ASP.NET MVC2 with EF4. I need to create POCOs for two of my classes PersonP and AddressP, which correspond to their EF4 'complex' classes (which include things like navigation properties and OnPropertyChanged()). Mapping just PersonP by itself works fine, but PersonP contains AddressP (foreign key) - how do I map this using an IQueryable expression?
Here is what I've tried:
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
//}
});
Without the
.Include("Address")
I would not retrieve anything from the Address table is this correct?How do I map
Address
toAddressP
insidePersonP
, using theSelect()
statement above?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的事情会起作用:
虽然这个解决方案可以解决问题,但如果目的是拥有 POCO 类,您绝对应该考虑利用 EF4.0 POCO 支持并直接在 EF 中使用 POCO 类,而不是事后映射它们。一个好的起点是这个演练:
演练:实体框架的 POCO 模板
Something like this will work:
While this solution will do the trick but if the intention is to have POCO classes you should definitely consider to take advantage of EF4.0 POCO support and use POCO classes directly with EF instead of mapping them afterward. A good place to start would be this walkthrough:
Walkthrough: POCO Template for the Entity Framework