You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6中使用Guid作为Identity的Id时遇类型转换异常

解决:无法将System.String转换为System.Guid的Identity查询错误

核心原因

你的ApplicationUser实体指定Id为Guid类型,但SQL Server中AspNetUsers表的Id字段类型不是uniqueidentifier,或者存储的Id数据格式与EF Core的Guid映射不兼容,导致查询时类型转换失败。

解决步骤

1. 修正数据库表字段类型

检查AspNetUsers表的Id字段类型,若为nvarchar/varchar,需改为uniqueidentifier:

ALTER TABLE AspNetUsers
ALTER COLUMN Id uniqueidentifier NOT NULL;

-- 可选:设置默认值为自动生成的Guid(推荐NEWSEQUENTIALID(),性能更优)
ALTER TABLE AspNetUsers
ADD CONSTRAINT DF_AspNetUsers_Id DEFAULT NEWSEQUENTIALID() FOR Id;

2. 修正现有数据(若表中已有数据)

如果表中存储的是字符串格式的Guid(如"3fa85f64-5717-4562-b3fc-2c963f66afa6"),执行转换:

UPDATE AspNetUsers
SET Id = CAST(Id AS uniqueidentifier)
WHERE Id LIKE '________-____-____-____-____________' -- 匹配标准Guid格式

3. 确认EF Core配置正确性

你的代码中以下配置已正确设置,无需修改:

  • ApplicationUser : IdentityUser<Guid>
  • IdentityDataBaseContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
  • AddIdentity<ApplicationUser, ApplicationRole>()

4. 检查迁移文件(Code First场景)

查看已生成的迁移文件,确保Id字段映射为uniqueidentifier:

migrationBuilder.CreateTable(
    name: "AspNetUsers",
    columns: table => new
    {
        Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
        // 其他字段...
    },
    constraints: table => table.PrimaryKey("PK_AspNetUsers", x => x.Id));

若之前迁移配置错误,重新生成并更新数据库:

Add-Migration FixUserIdType
Update-Database

5. 规范查询代码

避免将Guid转为字符串查询,直接使用Guid类型匹配:

// 正确写法
var targetId = Guid.Parse("3fa85f64-5717-4562-b3fc-2c963f66afa6");
var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == targetId);

内容的提问来源于stack exchange,提问作者babaei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:33:33