dapper nuget 1.7 枚举映射
我从 Nuget 升级到最新版本的 Dapper(v 1.7)后遇到了问题。
它始终返回第一个枚举成员(即,它无法映射)。
我使用 MySQL 作为数据库。
CREATE TABLE `users_roles` (
`userId` INT(11) NOT NULL,
`roleId` INT(11) NOT NULL,
KEY `user_id` (`userId`),
KEY `role_id` (`roleId`)
);
INSERT INTO `users_roles` (`userId`, `roleId`) VALUES (1, 1);
INSERT INTO `users_roles` (`userId`, `roleId`) VALUES (2, 2);
public enum Role {
Anonymous = 0, Authenticate = 1, Administrator = 2
}
var role = Current.Db.Query<Role>(@"SELECT roleId as Role FROM users_roles
WHERE userId=@id", new { id = 2 }).FirstOrDefault();
它给出了 Dapper nuget v1.6 中的预期输出。这是新版本(1.7)的正确行为吗?
更新:
在使用一些控制台应用程序和新的 mvc3 应用程序进行一些测试后,我发现当您直接映射枚举类型时,Dapper 枚举映射的行为不一致。
但是,将枚举映射为类的属性以某种方式始终返回正确的映射
public class User
{
public int Id { get; set; }
public Role Role { get; set; }
}
var user = Current.Db.Query<User>(@"SELECT roleId as Role, userId as Id
FROM users_roles
WHERE userId=@id", new { id = 2 }).FirstOrDefault();
user.Role 的结果以某种方式返回预期的输出
I've encountered an issue after I upgraded to the latest version of Dapper from Nuget (v 1.7).
It always return the first enums member (that is, it fail to maps).
I am using MySQL as the database.
CREATE TABLE `users_roles` (
`userId` INT(11) NOT NULL,
`roleId` INT(11) NOT NULL,
KEY `user_id` (`userId`),
KEY `role_id` (`roleId`)
);
INSERT INTO `users_roles` (`userId`, `roleId`) VALUES (1, 1);
INSERT INTO `users_roles` (`userId`, `roleId`) VALUES (2, 2);
public enum Role {
Anonymous = 0, Authenticate = 1, Administrator = 2
}
var role = Current.Db.Query<Role>(@"SELECT roleId as Role FROM users_roles
WHERE userId=@id", new { id = 2 }).FirstOrDefault();
It gives the expected output in Dapper nuget v1.6. Is this the correct behavior for the new version (1.7)?
Update:
After doing some testing with a few console application and fresh mvc3 appications I found that the behavior of Dapper enum mapping is inconsistent when you map the enum type directly.
However, mapping an enum as a property of a class somehow consistently returns the correct map
public class User
{
public int Id { get; set; }
public Role Role { get; set; }
}
var user = Current.Db.Query<User>(@"SELECT roleId as Role, userId as Id
FROM users_roles
WHERE userId=@id", new { id = 2 }).FirstOrDefault();
the result of user.Role somehow returns the expected output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在错误修复之前,我的解决方法是使用额外条件修改 GetDeserializer 方法
将 struct 反序列化器用于枚举,如下所示:
Until the bug is fixed my workaround is to modify GetDeserializer method with extra condition
to use struct deserializer for enums as follows: