I'm currently working through Getting Started with EF5 using MVC 4 in Visual Studio 2010 (.NET 4.0) to learn about how to use ASP.NET and Entity Framework. During the beginning of the tutorial I ran into an issue with enum support when creating a database with Code First Migrations. For reasons unknown I have to work in this environment and create my own support for enums so I decided to make the property int
instead then I would convert it to Enum when I want to display it like so:
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq;
using System.Linq.Expressions;
namespace ContosoUniversity.Extensions
{
public static class Extensions
{
public static String DisplayAsEnum<TModel, TValue>(this HtmlHelper<TModel> cHtml,
Expression<Func<TModel, TValue>> cExpression,
Type cType,
String strDisplay = "Unknown")
{
try
{
if (cType.IsEnum)
{
object cResult = cExpression.Compile().DynamicInvoke(cHtml.ViewData.Model);
if (cResult != null)
{
strDisplay = Enum.ToObject(cType, cResult).ToString();
}
}
}
catch (Exception cExc)
{
strDisplay = cExc.ToString();
}
return (strDisplay);
}
}
}
In my razor cshtml file I display it to the webpage with this call:
@Html.DisplayAsEnum(modelItem => item.Grade, typeof(Grade), "No Grade")
I have a feeling that this is not the "professional" or "right" way of handling the lack of enum support so I was wondering if there is anyway to improve this function or is there a better way of handling enumerations in EF 5 with .Net 4.0 support?
I was shown a Stack Overflow question that provides me with a better solution to handling the enum support. It is very helpful and I am using it at the moment, but since I do like the function that I made, is it possible to improve it?