Shawn Mclean
Shawn Mclean

Reputation: 57469

Knowing the Child type of an abstract class

I'm having problems designing a service layer when using a Table per Hierarchy setup with entity framework. My problem is that I am getting an object of a specific type but I want to check what the type is. This is better explained in codes:

Abstract Domain Class

public abstract class Order
{
    public string OrderId { get; set; }
}

The inherited class

public class OrderProduct : Order
{
    public List<OrderDetail> OrderDetails { get; set; }
}

public class OrderSubscription : Order
{
    public decimal Fee { get; set; }
    public DateTime? EndDate { get; set; }
}

So you can basically do this:

orderRepository.GetOrders();
//OR
orderRepository.GetOrders().OfType<OrderProduct>();
//OR
orderRepository.GetOrders().OfType<OrderSubscription>();

I'm basically using the first one. It returns IQueryable<Order>

I want to make 1 service layer method that makes the call that gets any type, for eg:

public Order GetOrder(string orderId)
{
    return orderRepository.GetOrders().FirstOrDefault(o => o.OrderId == orderId);
}

The Problem

In my controller, how can I tell what type the object is after making the call to GetOrder(string orderId)? If it is of the type OrderProduct, then I also need the navigational property (List<OrderDetail>) to be there when I cast it.

One solution to this I see is to make 2 types of service layer call for each Order class. Call 1, and if it returns null, then call the other. But is there an OOP way to do this in C#?

Upvotes: 2

Views: 1584

Answers (2)

Jan-Peter Vos
Jan-Peter Vos

Reputation: 3197

I'm not completely sure what you are asking but i think you are looking for the is operator:

Order order = //...    
bool isSubscription = order is OrderSubscription;

Also if you want to use the value after that you can also use as and this will cast it or return null it it's not of the type.

Order order = //...
OrderSubscription subscription = order as OrderSubscription;
if (subscription != null)
{
  // use subscription
}

Upvotes: 2

user47589
user47589

Reputation:

Order o = GetOrder("12345");
if (o is OrderProduct)
{
    var product = (OrderProduct)o;
}
else if (o is OrderSubscription)
{
    var subscription = (OrderSubscription)o;
}

Does this do what you need? I'm slightly fuzzy on what your needs are.

Upvotes: 0

Related Questions