Given that
public abstract class AbstractOrder
{
//some properties...
}
public class AnonymousOrder:AbstractOrder
{
//some properties...
}
public class PartnerOrder:AbstractOrder
{
//some properties...
}
public AbstractOrder FindOrderByConfirmationNumber(string confirmationNumber)
{
ICriteria criteria =
Session.CreateCriteria(typeof(AbstractOrder))
.SetMaxResults(10)
.AddOrder(Order.Desc("PurchasedDate"))
.Add(Restrictions.Eq("ConfirmationNumber", confirmationNumber));
var l = criteria.List<AbstractOrder>();
AbstractOrder ao = l[0] as AbstractOrder;
return ao as AbstractOrder;
}
Can someone please explain why
PartnerOrder order = repo.FindOrderByConfirmationNumber(confirmationNumber)
returns a type of AnonymousOrder and how I get it to return a type of PartnerOrder?
FindOrder is returning a type of
AbstractOrder; just look at its declaration. The object it returns may be an instance ofAnonymousOrder, but allAnonymousOrderinstances are alsoAbstractOrderinstances, becauseAnonymousOrderinherits fromAbstractOrder.I think your real problem is trying to assign an
AnonymousOrderinstance to aPartnerOrderreference. This won’t work, since neither type is derived from the other.This, however, will work:
Alternatively, you could test the type of the return value:
If you really need a PartnerOrder instance for a confirmationNumber that returns an AnonymousOrder, then you’ll need a method that takes an AnonymousOrder instance and returns a PartnerOrder instance. Or, perhaps, you should rethink your design.