简体   繁体   中英

Get type of Entity in EF TPT Inheritance

My domain entities are using EF Table Per Type Inheritance, and here is the relationship.

每种类型的表

As you can see Invoices sits on the parent entity Order.cs . This is now creating me issues when I deal with invoices.

For instance, to create an invoice , I need to pass the order Id to the Invoice controller:

public ActionResult Create(int orderId)
{
  if (orderId == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

  // determine whether the order is a SaleOrder or a PurchaseOrder
  // then create the viewModel passing in the SaleOrder / PurchaseOrder details
  return View(viewModel);
}

How do I figure out what child type an order is by simply its Id?

UPDATE

Theo asked how I was currently retrieving SaleOrders and PurchaseOrders. I have this in my context:

public DbSet<PurchaseOrder> PurchaseOrders { get; set; }
public DbSet<SaleOrder> SaleOrders { get; set; }

I have built a repository around each, so I have a PurchaseOrderRepository and a SaleOrderRepository and I do my CRUD that way.

If the two classes inherit from the same class you can create another DbSet

public DbSet<Order> Orders { get; set; }

and in your Action ask for the order like this

    public ActionResult Create(int orderId)
    {
      if (orderId == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      var order = db.Orders.Find(orderId);
      if(order is SaleOrder){
        //do your stuff for SaleOrder
      }
      if(order is PurchaseOrder){
        //do your stuff for PurchaseOrder
      }          
      return View(viewModel);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM