Ngugi1 / sqlite-net

Automatically exported from code.google.com/p/sqlite-net
0 stars 0 forks source link

convert int32 to Nullable<enum> #47

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. add a column of type int ( if using the wrapper class use Nullable<anyEnum> .
2. insert couple of records in the table.
3. select from that table

What is the expected output? What do you see instead?
-expected output : enumerable of that table
-output: crash "cannot convert int32 to Nullable<enum>"

What version of the product are you using? On what operating system?
-Windows 8 RT

Please provide any additional information below.
-The original code in  function "SetValue" located in 
"SQLite.TableMapping.Column" as as the following:

public void SetValue (object obj, object val)
{
   _prop.SetValue(obj, val, null);
}

I've changed it to the following and its working properly 

public void SetValue (object obj, object val)
{
  Type propType = _prop.PropertyType;
  if (propType.IsConstructedGenericType &&
      propType.GetGenericTypeDefinition() == typeof(Nullable<>))
  {
      Type[] typeCol = propType.GenericTypeArguments;
      Type nullableType;
      if (typeCol.Length > 0)
      {
          nullableType = typeCol[0];
          if (nullableType.GetTypeInfo().BaseType == typeof(Enum))
          {
              object result = Enum.Parse(nullableType, val.ToString());
              _prop.SetValue(obj, result, null);
          }
          else
          {
              _prop.SetValue(obj, val, null);
          }
      }
  }
  else
  {
      _prop.SetValue(obj, val, null);
  }
}

Original issue reported on code.google.com by younes.a...@gmail.com on 22 Nov 2012 at 2:55

GoogleCodeExporter commented 9 years ago
you have a bug here, as if "val" is of Nullable<enum> and actual value is null 
then conversion ".ToString()" will crash. Change that line to :

object result = val==null?null:Enum.Parse(nullableType, val.ToString());

and it will work fine

Original comment by Mariusz....@gmail.com on 5 Dec 2012 at 3:16