如何使用SqlDataReader获取IdentityUser名称并解决类型转换错误
解决方案
1. 修正Model属性类型
数据库中存储的UserId是字符串(或Guid)类型,而非完整的IdentityUser对象,因此需要调整Model的属性定义:
public class Model { // 改为与数据库存储类型匹配的字符串(若数据库存Guid则用Guid类型) public string UserId { get; set; } // 可选:若需关联完整用户信息,添加EF Core导航属性 public IdentityUser User { get; set; } public string data { get; set; } public decimal data2 { get; set; } public DateTime data3 { get; set; } }
2. 修复SqlDataReader读取逻辑
调整读取代码,直接读取字符串类型的UserId,解决类型转换错误:
using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); // 异步打开连接更规范 string sql = "SELECT UserId, data, data2, data3 FROM Table;"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) // 异步读取提升性能 { Model test = new Model { UserId = reader.GetString(0), // 类型匹配,可直接读取 data = reader.GetString(1), data2 = reader.GetDecimal(2), data3 = reader.GetDateTime(3) }; list.Add(test); } } } }
3. 在Blazor页面展示用户详细信息(可选)
若需要展示用户的用户名、邮箱等信息,可注入UserManager<IdentityUser>,通过UserId查询对应用户:
@inject UserManager<IdentityUser> UserManager <table> <thead> <tr> <th>用户名</th> <th>Data</th> <th>Data2</th> <th>Data3</th> </tr> </thead> <tbody> @foreach (var item in list) { <tr> <td>@(await GetUserName(item.UserId))</td> <td>@item.data</td> <td>@item.data2</td> <td>@item.data3</td> </tr> } </tbody> </table> @code { private List<Model> list = new(); private async Task<string> GetUserName(string userId) { var user = await UserManager.FindByIdAsync(userId); return user?.UserName ?? "未知用户"; } // 数据初始化逻辑... }
补充说明
- 不要直接在数据库存储完整的
IdentityUser对象,标准做法是存储用户ID作为外键,需要时通过UserManager查询完整信息。 - 确保数据库中
UserId字段类型与Model中的UserId类型一致(例如均为nvarchar)。
内容的提问来源于stack exchange,提问作者leonard staniloiu
相关产品推荐
相关产品推荐

