All work

Select view

Select search mode

 
50 of 90

Enums in LINQ query do not provide correct values for SQL statement parameters

Description

Using enums inside of WHERE criteria produces correct SQL statement, but value is calculated improperly.
In my case I map enum to varchar2 column and use NHibernate.Type.EnumStringType class to handle value mapping. When an object with enum property is saved, the value sent to GetValue() method is of enum type. But when LINQ query is executed the value passed to GetValue() method is not an enum but an integer.
To handle this issue I used additional piece of code if value is of int type -

public enum Formula {
fNone,
fRatio,
fXXX
}

public class Formula_Map : NHibernate.Type.EnumStringType {
public Formula_Map() : base(typeof(Formula)) {}
public override object GetInstance(object code) {
try {
switch(code as string) {
case "None": return Formula.fNone;
case "Ratio": return Formula.fRatio;
case "XXX": return Formula.fXXX;
}
return Formula.fNone;
}
catch (ArgumentException ae) {
throw new NHibernate.HibernateException(string.Format("Can not Parse {0} as {1}", code, ReturnedClass.Name), ae);
}
}
public override object GetValue(object code) {
if (code == null)
return "?";
else {
if (Enum.Equals(code, Formula.fNone)) return "None";
if (Enum.Equals(code, Formula.fRatio)) return "Ratio";
if (Enum.Equals(code, Formula.fXXX)) return "XXX";

// — the following code is a workaround to handle situation
// — when the value is an integer, not enum
if (code is int)
{
switch ((int)code)
{
case(0): return "None";
case(1): return "Ratio";
case(2): return "XXX";
}
}
return "??";
}
}
}

Environment

None

Details

Assignee

Reporter

Components

Affects versions

Priority

Who's Looking?

Open Who's Looking?
Created March 11, 2011 at 12:39 PM
Updated March 11, 2011 at 12:39 PM

Activity

Show:
Who's Looking?