简体   繁体   中英

Unable to check type of entity of base/inherited classes

I am having an issue with getting the types of a class based on using GetType() and typeof(), the issue being that it isn't working.

I have base class of Content and inherited classes of Podcast and AudioBook.

I am using Code First and have a Table per Hierarchy (which stores all child classes in one table with a Discriminator column) to store all the Content entities.

I want to query the Content table by the Title column, and return a Content entity. Then, based on the type (Podcast, AudioBook) do some other things. However the type check isn't working.

Models

public abstract class Content
{ 
    public string Title { get; set; }
}

public class Podcast : Content
{

}

Repository

public Content FindContentByRoutingTitle(string routingTitle)
{
    var content = Context.ContentItems
    .FirstOrDefault(x => x.RoutingTitle == routingTitle);

    return content;
}

Controller

var content = _contentRepository.FindContentByRoutingTitle(title);

if (content.GetType() == typeof(Podcast))
{
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else if (content.GetType() == typeof(Content))
{
    //just a check to see if equating with Content
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else
{
    //if/else block always falls to here.
    return RedirectToAction("NotFound", "Home");
}

Is there something I am missing here? Thanks for your help.

Reference: Type Checking: typeof, GetType, or is?

GetType() returns the actual class of the object so if you try to compare it to typeof(Content) you will get false . However If you want to check if the variable derives from a base class I recommend 2 options.

  • Option 1:

     if (content is Content) { //do code here } 
  • Option 2:

     if (content.GetType().IsSubclassOf(typeof(Content))) { //do code here } 

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