Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc inheritance controllers

I'm studing asp.net mvc and in my test project I have some problems with inheritance: In my model I use inheritanse in few entities:

public class Employee:Entity
    {
        /* few public properties */
    }

It is the base class. And descendants:

public class RecruitmentOfficeEmployee: Employee
    {
        public virtual RecruitmentOffice AssignedOnRecruitmentOffice { get; set; }
    }

public class ResearchInstituteEmployee: Employee
    {
        public virtual ResearchInstitute AssignedOnResearchInstitute { get; set; }
    }

I want to implement a simple CRUD operations to every descedant.

What is the better way to inplement controllers and views in descendants: - One controller per every descendant; - Controller inheritance;
- Generic controller; - Generic methods in one controller.

Or maybe there is an another way?

My ORM is NHibernate, I have a generic base repository and every repository is its descedant. Using generic controller, I think, is the best way, but in it I will use only generic base repository and extensibility of the system will be not very good.

Please, help the newbie)

like image 900
Ris90 Avatar asked Feb 01 '26 12:02

Ris90


1 Answers

It really depends on how much shared logic there is and how your want your application to flow.

If most of the logic is the same, I would say reuse a single controller and create views that match each inherited type. You would load the appropriate repository, domain objects, and view depending on the type. The type could be determined by a parameter, routing, or some other lookup determined in an action filter.

Here's an example of doing it by passing in a parameter (the easiest technique IMO):

public class EmployeeController : Controller
{
    public enum EmployeeType
    {
        RecruitmentOffice,
        ResearchInstitute
    }

    public ActionResult Details(int id, EmployeeType type)
    {            
        switch (type)
        {
            case EmployeeType.RecruitmentOffice:
                // load repository
                // load domain object
                // load view specific to recruitment office
                break;
            case EmployeeType.ResearchInstitute:
                // load repository
                // load domain object
                // load view specific to recruitment office
                break;
        }
    }
}
like image 55
bmancini Avatar answered Feb 03 '26 07:02

bmancini