Dapper:不允许从数据类型 datetime 到 int 的隐式转换。使用 CONVERT 函数 运行 这个查询

Dapper: Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query

我有这个用于将用户插入数据库的查询:

INSERT INTO [User] 
OUTPUT inserted.Id 
VALUES (@IsDelete, @FirstName, @LastName, @UserName, @Email, @Birthdate, @IsActive, @Password, @SecurityStamp, @Gender, @ActivetionCode, @ActivationCodeExpireDateTime)

这是我的模型:

User user = new User();
user.Email = request.Email;
user.IsDelete = false;
user.IsActive = false;
user.Birthdate = DateTime.UtcNow;
user.FirstName = "user" + DateTime.Now.Millisecond;
user.LastName = "failmy" + DateTime.Now.Millisecond;
user.Password = request.Password;
user.UserName = request.UserName;
user.Gender = GenderEnum.Male;
user.SecurityStamp = Guid.NewGuid();
user.ActivetionCode = code;
user.ActivationCodeExpireDateTime = DateTime.UtcNow;

我在这里使用它:

var role = roleConnection.Query<int>(Command, Model);

但我收到此错误:

Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.

有什么问题吗?我该如何解决?

如评论所述:您的值列表和列列表之间可能存在不匹配,最终导致将值写入不属于它的列。

您使用的插入语法未列出目标列:

insert into [User] output inserted.Id values(val1, val2, ...)

这很容易出错,而且当出现问题时很难调试。相反,您应该在插入查询中枚举列:

insert into [User](col1, col2, ...) output inserted.Id values(val1, val2, ...)) 

使用此语法可以更轻松地检查列和值是否匹配。