Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified Cast is not Invalid (Enum with int value, Dapper)

Tags:

dapper

I have a class with a (simple, first cut) implementation of user roles:

class User { 
  public Role Role { get; set; }
  // ...
  public User() { this.Role = Role.Normal; }
  public void Save() { Membership.CreateUser(...) } // System.Web.Security.Membership
} 

enum Role : int {
  Invalid = 0,
  Normal = 1,
  SuperUser = 4096
}

Before adding the role, everything worked fine (if that matters).

Now, when I try to fetch users, this line fails:

toReturn = conn.Query<User>("SELECT TOP 1 * FROM dbo.UserProfile WHERE 1=1");

The stack trace (from ELMAH):

System.Data.DataException: Error parsing column 2 (Role=1 - Int16) ---> System.InvalidCastException: Specified cast is not valid.
   at Deserialize06df745b-4fad-4d55-aada-632ce72e3607(IDataReader )
   --- End of inner exception stack trace ---
   at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 2126
   at Deserialize06df745b-4fad-4d55-aada-632ce72e3607(IDataReader )
   at Dapper.SqlMapper.<QueryInternal>d__d`1.MoveNext() in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 827
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper\SqlMapper.cs:line 770

In the database, the column type for Role is smallint.

I'm using Dapper 1.12.1 from NuGet.

like image 525
ashes999 Avatar asked Jun 30 '26 04:06

ashes999


1 Answers

Gah. The answer was to make the database and class definitions match.

For smallint (which is what MigratorDotNet generated for me), I needed the enum to derive from short, not int. Everything works now.

Possibly useful Google Code issue: https://code.google.com/p/dapper-dot-net/issues/detail?id=32

like image 199
ashes999 Avatar answered Jul 01 '26 17:07

ashes999



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!