Wednesday, April 20, 2011

How to show numerical status in MVC application

I am building a new application based on MVC and considering LINQ-To-SQL/Entity Framework. I a have entity which has a numerical status Like (0 - Open, 1 - Active, 2 - Closed), Where should i Put the logic to show appropriate string (Enum??) in the view/controller or model which is generated automatically? Should I move all such logic into business layer? Should I add business logic and a new property (To show the string status) to the partial classes build by LINQ-To-SQL?

From stackoverflow
  • Actually, LINQ-to-SQL can bind integers directly to enums (to either int (etc) or [n][var]char columns data at the database), so a simple answer is to create an enum (in your data/repository layer), and change the dbml (usually via the designer) so that it uses the (fully-qualified) enum type for the status column.

    If this isn't an option, then I would rename the status property in the class (again via the dbml) to something like StatusCode, and add a partial class that returns the preferred representation (as either an enum or a string) i.e.

    partial class YourType { // only do this if direct enum mapping isn't an option
        public Status Status { // could also be string
             get {
                 switch(StatusCode) {
                      case 0: return Status.Open;
                      // etc
                 }
             }
        }
    }
    
    Lucas : wouldn't casting the int directly to the enum type be better than switch/case? get { return (Status)StatusCode; }
    Marc Gravell : @Lucas - if they could cast directly, then they could (largely by definition) use the simpler LINQ-to-SQL binding...

0 comments:

Post a Comment