指定的Cast无效(带有int值的枚举,Dapper) [英] Specified Cast is not Invalid (Enum with int value, Dapper)

查看:79
本文介绍了指定的Cast无效(带有int值的枚举,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");

堆栈跟踪(来自ELMAH):

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

在数据库中,角色的列类型为 smallint

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

我正在使用N中的Dapper 1.12.1 uGet。

I'm using Dapper 1.12.1 from NuGet.

推荐答案

Gah。答案是使数据库和类定义匹配。

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

对于 smallint (这是MigratorDotNet为我生成的内容) ),我需要枚举从 short 而不是 int 导出。现在一切正常。

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

可能有用的Google代码问题: https://code.google.com/p/dapper-dot-net/issues/detail?id=32

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

这篇关于指定的Cast无效(带有int值的枚举,Dapper)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆