开发者

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#?


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜