Domanda

I use this code to filter database records

if (!string.IsNullOrEmpty(_searchCriteria.MessageType))
        {
            var messageType = (AutotransferMessageType)Enum.Parse(typeof(AutotransferMessageType), _searchCriteria.MessageType, true);
            if (Enum.IsDefined(typeof(AutotransferMessageType), messageType))
            {
                criteriaQuery.CreateAlias("AutotransferInputRecord", "AutotransferInputRecord")
                    .Add(
                        Restrictions.Eq(
                            "AutotransferInputRecord." + AutotransferLogSearchCriteria.MessageTypePropertyName,
                            messageType));
            }
            else
            {
                criteriaQuery.Add(Restrictions.IsNull("AutotransferInputRecord"));
            }
        }

AutotransferMessageType is enumerable type

public enum AutotransferMessageType
    {
        [DisplayName("MT202")]
        [DatabaseName("MT202")]
        MT202,
        [DisplayName("MT210")]
        [DatabaseName("MT210")]
        MT210,
            //...
}

My filter outputs the results when I enter MT202, for example. (It's the right behavior).
When I input just number, for example, 202, I get no results (It's the right behavior too). But when I try to input some line, "mt", for example, I get error
Unexpected application error has been occured:
'Requested value 'mt' was not found.'

How to make the filter do not show any results when I input a line?

È stato utile?

Soluzione

Your error is coming from the line that parses the enum. Use Enum.TryParse instead:

AutotransferMessageType msgEnum;
var enumPrasedOk = Enum.TryParse(_searchCriteria.MessageType, true, out msgEnum);
if(enumPrasedOk){
    //Do something
}else{
    //Handle case where enum was not found for some reason (if need be)
}

Also please note that you can not look up the enum this way using it's description (in your case they are the same so it is ok).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top