Elias Garcia
Elias Garcia

Reputation: 7282

Find an object with inheritance in Entity Framework

I have the database model as you can see in the screenshot below.

enter image description here

I want to display a Product in a page with the derived attributes (isbn if it's a book or pegi if it's a game for example). What is the best method to retrieve a Product from the web layer? Now I have a method FindProduct(long productId) that retrieves a product, but how can I get it's derived instance? (I have a ProductDao, BookDao and GameDao)Thanks.

public Product FindProduct(long productId)
{
    return ProductDao.Find(productId);
}

Upvotes: 0

Views: 68

Answers (1)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

This example shows how you can achive it in case of using ASP.NET MVC/Core If you don't want to use dynamic, than you can replace it on is..as chain.

public class ProductController : Controller
{
  public ViewResult Product(long productId) 
  {
      var product = FindProduct(productId);
      var productView = GetRelevantProductView((dynamic)product);
      return productView; 
  }

  private void GetRelevantProductView(Book book)
  {
    return View("BookView", book);
  }

  private void GetRelevantProductView(Game game)
  {
    return View("GameView", game);
  }

}

Upvotes: 1

Related Questions