views:

232

answers:

3

If a flag IsAdmin, cast as AdminUser otherwise cast as NormalUser.

Was just curious about this but not sure how to do it. I do see that you can create a child object based on a table value and another table like:

SiteUser is from the table Site_User AdminUser is from the table Site_User and Admin_User when Site_User.IsAdmin = true

However, I was curious if you could do this:

If IsAdmin is true, cast as AdminUser otherwise cast as NormalUser where AdminUser : SiteUSer and NormalUser : SiteUser BUT there isn't a Admin_User table or Normal_User table. This is strictly a casting based off the same table and a column value. The types hold no additional information, just would be helpful for situations like:

SomeMethod(SiteUser someUser)
{
    if(someUser is AdminUser)
    {
       ...
    }
    else
    {
       ...
    }
}

Instead of:

SomeMethod(SiteUser someUser)
{
    if(someUser.IsAdmin)
    {
       ...
    }
    else
    {
       ...
    }
}

Now I realize this may not be the best example, but say the flag is a multiple value property so instead of:

SomeMethod(SiteUser someUser)
{
    swith(someUser.Role)
    {
        case(1):
          break;
        case(2)
          break;
    }
}

Of course this just might be a bad idea anyhow, but was wondering if it is possible.

A: 

As a rule of thumb, checking if an object is an instance of a given class is not good practice. Try using a method or property instead (someUser.isAdmin()).

Anyways, I'm not sure what your question is ?

Wookai
Yeah you're probably right on the first part, and second part doesn't surprise me since I wasn't 100% sure how to ask.
Programmin Tool
+2  A: 

Entity framework supports Table-Per-Type and Table-Per-Hierarchy inheritance.

Table-Per-Type means that a new table is used for each class, including the abstract type. Table-Per-Hierarchy means that a single table is used to store data for multiple types, and only the columns necessary for that type are pulled from the single table.

Either way, an object can be tested just the way you are describing.

if (someUser is AdminUser)
{
   ...
}
else
{
   ...
}

More information on using both of these can be found here, and they both are supported visually in the Entity Framework designer:

Table-Per-Type

Table-Per-Hierarchy

Lusid
A: 

I also found this after looking at the two articles above:

http://weblogs.asp.net/zeeshanhirani/archive/2008/08/16/single-table-inheritance-in-entity-framework.aspx

This give a UI example of what I was trying to do. Kind of nice.

Programmin Tool