I've got a collection of addresses which can contain multiple addresses for a Customer (delivery, invoice, etc.)
Now, I'm trying to use .Include(s => s.Addresses)
on my Customer class. Addresses and the derivative DeliveryAddress are defined like this:
protected virtual ICollection<Address> Addresses
{
get { return _addresses ?? (_addresses = new Collection<Address>()); }
set { _addresses = value; }
}
[NotMapped]
public Address DeliveryAddress
{
get { return GetAddress(AddressType.Delivery); }
}
private Address GetAddress(AddressType type)
{
return Addresses.FirstOrDefault(a => a.Type == type);
}
Since it's a protected property, I've found a solution for this on Mapping but not exposing ICollections in Entity Framework
I Also found the following post, but this is about mappings instead of includes: How to map a protected property in EF 4.3 code first
Here they add the following to the class containing the protected property public static Expression<Func<Parent, ICollection<Child>>> ChildrenAccessor = f => f.ChildrenStorage;
.
So I've added the same to my Customer class like so:
public static Expression<Func<Customer, ICollection<Address>>> AddressesAccessor = f => f.Addresses;
And then i'm able to use the include with Include(Customer.AddressesAccessor)
This works great for mappings, but I'm not getting it to work with the Include method. It keeps telling me the following:
System.InvalidOperationException: A specified Include path is not valid. The EntityType 'Web.DataAccess.Customer' does not declare a navigation property with the name 'Addresses'.
When I change the signature of the Addresses property from protected
back to public
all works fine.
Does anyone know how to make this work for protected collections?