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

北城以北 提交于 2019-12-23 18:40:06

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/15437851/specified-cast-is-not-invalid-enum-with-int-value-dapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!