Reafidy
Reafidy

Reputation: 8481

Return Enum Name from Integer in LINQ Database Query

I would like to return the string value of an enum stored as an integer in a database using a LINQ query.

What I have tried:

  return (from a in context.Tasks
                    select new TaskSearch
                    {
                        TaskID = a.TaskID,
                        TaskTypeName = Enum.GetName(typeof(TaskTypeEnum), a.TaskType)
                    }).ToList();

I'm using asp.net mvc.

Exception: An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'System.String GetName(System.Type, System.Object)' method, and this method cannot be translated into a store expression.

Upvotes: 1

Views: 4710

Answers (3)

Ibrahim Ali Asghar
Ibrahim Ali Asghar

Reputation: 1

Your error shows that query is unable to understand the Enum.GetName() method. You can cater this problem by just typeCasting your integer value in the query.

Try

((from a in context.Tasks select a).AsEnumerable().Select(t => new 
    TaskSearch
    {
       TaskID = t.TaskID,
       TaskTypeName = (TaskTypeEnum)t.TaskType
}).ToList());

Upvotes: -1

user3559349
user3559349

Reputation:

You need to materialize your query (a query must be able to be converted to a sql statement, but Enum.GetName() cannot be converted to sql)

Try

((from a in context.Tasks select a).AsEnumerable().Select(t => new TaskSearch
{
  TaskID = t.TaskID,
  TaskTypeName = Enum.GetName(typeof(TaskTypeEnum), t.TaskType)

}).ToList());

Upvotes: 4

Pieter Geerkens
Pieter Geerkens

Reputation: 11893

I define a set of Enum extensions like this which I have found useful. Unfortunately the Type constraints cannot be refined beyond struct, so you must externally ensure that the methods are only called on Enums.:

/// <summary>Type-safe extension methods for parsing Enums.</summary>
public static partial class EnumExtensions{
  #region Enum Parsing utilities
  /// <summary>Typesafe wrapper for <c>Enum.GetValues(typeof(TEnum).</c></summary>
  public static ReadOnlyCollection<TEnum> EnumGetValues<TEnum>() {
    return new ReadOnlyCollection<TEnum>((TEnum[])(Enum.GetValues(typeof(TEnum))));
  }

  /// <summary>TODO</summary>
 [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
  public static ReadOnlyCollection<string> EnumGetNames<TEnum>() where TEnum : struct {
    return new ReadOnlyCollection<string>((string[])(Enum.GetNames(typeof(TEnum))));
  }

  /// <summary>Typesafe wrapper for <c>Enum.ParseEnum()</c> that automatically checks 
  /// constants for membership in the <c>enum</c>.</summary>
  public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct {
    return ParseEnum<TEnum>(value,true);
  }

  /// <summary>Typesafe wrapper for <c>Enum.ParseEnum()</c> that automatically checks 
  /// constants for membership in the <c>enum</c>.</summary>
  public static TEnum ParseEnum<TEnum>(string value, bool checkConstants) where TEnum : struct {
    TEnum enumValue;
    if (!TryParseEnum<TEnum>(value, out enumValue) && checkConstants) 
          throw new ArgumentOutOfRangeException("value",value,"Enum type: " + typeof(TEnum).Name);

    return enumValue;
  }

  /// <summary>Typesafe wrapper for <c>Enum.TryParseEnum()</c> that automatically checks 
  /// constants for membership in the <c>enum</c>.</summary>
  public static bool TryParseEnum<TEnum>(string value, out TEnum enumValue) where TEnum : struct {
    return Enum.TryParse<TEnum>(value, out enumValue)  
       &&  Enum.IsDefined(typeof(TEnum),enumValue);
  }

  /// <summary>Typesafe wrapper for <c>Enum.ToObject()</c>.</summary>
  /// <typeparam name="TEnum"></typeparam>
  public static TEnum EnumParse<TEnum>(char c, string lookup) {
    if (lookup==null) throw new ArgumentNullException("lookup");
    var index = lookup.IndexOf(c);
    if (index == -1) throw new ArgumentOutOfRangeException("c",c,"Enum Type: " + typeof(TEnum).Name);

    return (TEnum) Enum.ToObject(typeof(TEnum), index);
  }
  #endregion
}

Upvotes: 0

Related Questions