获取用户下拉列表遇UserID异常及smallint与uniqueidentifier类型冲突
解决下拉列表返回全0GUID和类型冲突错误的方案
看起来你遇到的两个问题是连锁反应——类型不匹配导致查询出错,进而返回了默认的全0GUID。咱们一步步来解决:
1. 先搞定「Operand type clash: smallint is incompatible with uniqueidentifier」错误
这个错误指向很明确:你的数据库字段类型和实体类属性类型不匹配。
- 先去检查
DojoDB.dbo.System_User表的UserID字段类型,它应该是smallint(或int)类型,但你的实体类rpusers里把UserID定义成了Guid类型,这就导致查询时出现类型冲突。
解决方案:
把实体类里的UserID类型改成对应的数据类型:
public class rpusers { // 将Guid改为int(数据库是smallint的话,int也完全兼容) public int UserID { get; set; } public string UserFirstname { get; set; } public string UserSurname { get; set; } public string FullName { get { return UserFirstname + " " + UserSurname; } } // 其他属性保持不变 public int InstanceID { get; set; } public int IsDeleted { get; set; } public List<rpusers> rpusersList { get; set; } public List<rpusersRecord> rpusersRecordList { get; set; } }
2. 解决下拉列表返回全0GUID的问题
这个问题源于存储过程返回的字段名和实体类属性名不匹配,导致ORM无法正确赋值:
你的存储过程里写了SELECT [UserID] AS ID,返回的字段名是ID,但实体类里的属性是UserID,所以查询结果无法映射到UserID属性,最终它用了Guid类型的默认值——全0GUID。
解决方案二选一:
方案A:修改存储过程,移除字段别名
ALTER PROC [dbo].[rpGetUsers] AS BEGIN SELECT [UserID], [UserFirstname] ,[UserSurname] FROM [DojoDB].[dbo].[System_User] END
方案B:给实体类属性加列名映射(不想改存储过程时用)
在UserID属性上添加[Column("ID")]特性(需要引用System.ComponentModel.DataAnnotations.Schema命名空间):
using System.ComponentModel.DataAnnotations.Schema; public class rpusers { [Column("ID")] public int UserID { get; set; } // 其他属性不变 }
3. 最后检查下拉列表代码
确保SelectList的参数对应正确:
@Html.DropDownListFor(m => m.FullName, new SelectList(Model.rpusersList, "UserID", "FullName"), "请选择用户", new { @class = "form-control" })
(这里补充了默认提示文本和基础样式,你可以根据实际需求调整)
做完这些修改后重新运行程序,应该就能拿到正确的UserID值,类型冲突的错误也会同步消失啦!
内容的提问来源于stack exchange,提问作者zufuzoje
相关产品推荐
相关产品推荐

