IQueryable Entity Framework POCO Mappings
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 retriev开发者_如何转开发e anything from the Address table is this correct?How do I map
Address
toAddressP
insidePersonP
, using theSelect()
statement above?
Thank you.
- That is correct, if you've disable Lazy Loading or your object context has been disposed already and cannot be used to get Lazy Loading working.
- Yes, it won't work since first you need to execute your query and then start mapping it, otherwise your mapping logic would be taken to be run in the database hence the exception.
Something like this will work:
// 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();
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
精彩评论