Otis wrote:
The collection _customer.QryCustomerAdress can have different types. As the relation is between Customer and Address (the supertype/root of the hierarchy), the collection, when fetched, can have instances of Address and any of the subtypes of Address.
so if you have Address and teh subtypes: BillingAddress and ShippingAddress, these are siblings in the hierarchy. If you traverse the collection _customer.QryCustomerAdress, you can't assume the instances in that collection are all BillingAddresses as it can be one address is a shippingaddress. As these are siblings, you can't cast from one to the other. This means that if you do:
for each BillingAddress address in _customer.QryCustomerAdress
....
next
this will crash if _customer.QryCustomerAdress contains a ShippingAddress, as the for each loop will cast the instance to BillingAddress below the surface, at least try to do so, which of course fails.
So what you should do is:
for each AddressEntity address in _customer.QryCustomerAdress
' check here the discriminator field in address and based on that cast.
next
I'm having a similar issue, but I'm not seeing how you would cast from the supertype to the subtype. How can you cast from Address to BillingAddress without getting a cast error?
In my case, I'm fetching a collection of CalendarItems, each of which could be an EventEntity or a TaskEntity. In this specific code, I only care about the first EventEntity (there should always be 0 or 1) and my return value must be typed as EventEntity.
private EventEntity _GetEvent(EventEntity.EventTypes type)
{
foreach (CalendarItemEntity ci in this.CalendarItems)
{
if (ci.EntityType == (byte)EntityTypes.Event)
{
// Checking the descriminator gets me here, but how do I return the EventEntity?
// These lines both error (as expected, since you can't cast to a more specific type, right?):
// EventEntity evt = (EventEntity)ci;
// EventEntity evt = ci as EventEntity;
if (evt.EventType == type)
{
return evt;
}
}
}
return null;
}
Maybe it's too late at night and I'm just too sleepy to figure it out?