これは、説明属性を取得する列挙型拡張メソッドです。
public static string GetDescription(this Enum enumeration)
{
if (enumeration == null)
throw new ArgumentNullException();
var value = enumeration.ToString();
var type = enumeration.GetType();
var descriptionAttribute =
(DescriptionAttribute[]) type.GetField(value).GetCustomAttributes(typeof (DescriptionAttribute), false);
return descriptionAttribute.Length > 0 ? descriptionAttribute[0].Description : value;
}
ソース オブジェクトは次のとおりです。
public class Account {
public int AccountId {get;set;}
public int AccountStatusId {get;set;}
}
列挙型は次のとおりです。
public enum AccountStatus {
[Description("N/A")]
None,
[Description("OPEN")]
Open,
[Description("CLOSED")]
Closed,
[Description("BAD CREDIT")
Problem
}
宛先オブジェクトは次のとおりです。
public class GetAccountResponse {
public int AccountId {get;set;}
public string Status {get;set;}
}
これが私のマッピングの試みです(最新の非静的オートマッパーバージョンを使用)。これは、EF クエリ可能なプロジェクションの間であることを思い出してください。
_config = new MapperConfiguration(cfg => cfg.CreateMap<Account, GetAccountsResponse>()
.ForMember(dest => dest.Status,
opts => opts.MapFrom(src => ((AccountStatus) src.AccountStatusId).GetDescription())));
クエリが である射影は次のIQueryable<Account>
とおりです。
query.ProjectToList<GetAccountResponse>(_config);
これは私が得る例外です:
これをクエリ可能な式に解決できません