开发者

Reference ENUM description when building selectList for dropdown list control

I have a form view model class that populates Select Lists for use by my views. Below is an extract from a section that creates a SelectList. The problem is that its a lookup table containing 2 other keys

        var waterIndicatorValues = waterIndicator
            .OrderBy(u => u.WaterIndicatorDescription)
            .Select(u => new KeyValuePair<int, string>(u.WaterIndicatorId, u.WaterIndicatorDescription + " [" + u.UnitTypeId.ToString() + "] " + u.HazardTypeId.ToString()));
        this.WaterIndicatorList = new SelectList(waterIndicatorValues, "Key", "Value", water.WaterIndicatorId);

Instead of UnitTypeId and HazardTypeId I want the text descriptions associated with those Id's. So i'd like my code to look like this :

        var waterIndicatorValues = waterIndicator
            .OrderBy(u => u.WaterIndicatorDescription)
            .Select(u => new KeyValuePair<开发者_运维百科;int, string>(u.WaterIndicatorId, u.WaterIndicatorDescription + " [" + u.UnitTypeId.ToDescription() + "] " + u.HazardTypeId.ToDescription()));
        this.WaterIndicatorList = new SelectList(waterIndicatorValues, "Key", "Value", water.WaterIndicatorId);

This code returns error "Method 'System.String ToDescription(System.Enum)' has no supported translation to SQL."

Any comments/help greatly appreciated

ENUM for UnitTypeId:

using System.ComponentModel;

namespace Emas.Model.Enumerations
{
    /// <summary>
    /// Defines the Unit Types.
    /// </summary>
    public enum UnitType
    {
        [Description("- Please Select -")]
        Blank = 0,

        [Description("kWh")]
        kWh = 1,

        [Description("m3")]
        m3 = 2,

        [Description("litres")]
        litres = 3,

        [Description("Kg")]
        Kg = 4,

        [Description("Unit(s)")]
        Unit = 5,

    }
}


You can't use extension methods within LINQ that pulls data from the database as it cannot be convert this extension code into SQL. You can however use ToArray() or ToList() to trigger the database hit and then use your extension methods on the result in memory instead.

Update:

Based on what you're trying to achieve in your updated code, I think this article may have the answer you need. You'll need to cast to the enum type too of course.

Update 2:

Converting into memory using ToList() before doing the select with extensions should work ok like below:

    var waterIndicatorValues = waterIndicator
        .OrderBy(u => u.WaterIndicatorDescription)
        .ToList()
        .Select(u => new KeyValuePair<int, string>(u.WaterIndicatorId, u.WaterIndicatorDescription + " [" + u.UnitTypeId.ToDescription() + "] " + u.HazardTypeId.ToDescription()));
    this.WaterIndicatorList = new SelectList(waterIndicatorValues, "Key", "Value", water.WaterIndicatorId);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜