我想使用LINQ查询返回在数据库中存储为整数的枚举的字符串值。
我尝试过:
return (from a in context.Tasks
select new TaskSearch
{
TaskID = a.TaskID,
TaskTypeName = Enum.GetName(typeof(TaskTypeEnum), a.TaskType)
}).ToList();
我使用的是asp.net mvc。
异常: 类型' System.NotSupportedException'的例外情况发生在EntityFramework.SqlServer.dll中但未在用户代码中处理
附加信息:LINQ to Entities无法识别方法' System.String GetName(System.Type,System.Object)'方法,并且此方法无法转换为商店表达式。
答案 0 :(得分:4)
您需要实现查询(查询必须能够转换为sql语句,但Enum.GetName()
无法转换为sql)
尝试
((from a in context.Tasks select a).AsEnumerable().Select(t => new TaskSearch
{
TaskID = t.TaskID,
TaskTypeName = Enum.GetName(typeof(TaskTypeEnum), t.TaskType)
}).ToList());
答案 1 :(得分:0)
我定义了一组这样的Enum扩展,我发现它很有用。不幸的是,类型约束不能超出struct
,因此您必须从外部确保仅在枚举上调用方法。
/// <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
}