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#?
I’m not completely sure what you are asking but i think you are looking for the
isoperator:Also if you want to use the value after that you can also use
asand this will cast it or returnnullit it’s not of the type.