.NET比较long值时出现System.Int32转System.String类型转换异常
问题:MySQL与.NET实体类型不匹配导致InvalidCastException错误
我有一个MySQL数据库,其中Medical_Record表包含long类型的NHSNumber字段。在.NET项目中,对应的Medical_Record实体类将NHSNumber定义为long类型,DB Context已成功创建。但在控制器中,将该字段与同样为long类型的参数id比较时,抛出错误:System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'。多次检查数据类型并尝试显式转换后仍未解决,不清楚为何会出现Int32与String的转换报错。
实体类代码
public class Medical_Record { [Key] public int doseNo { get; set; } public long NHSNumber { get; set; } public DateTime VaccinationDate { get; set; } public string? VaccineManufacturer { get; set; } public string? DiseaseTargeted { get; set; } public string? VaccineType { get; set; } public string? Product { get; set; } public string? VaccineBatchNo { get; set; } public string? CountryOfVaccination { get; set; } public string? Authority { get; set; } public string? Site { get; set; } public int TotalSeriesOfDoses { get; set; } public string? DisplayName { get; set; } public int SnomedCode { get; set; } public DateTime DateEntered { get; set; } public int ProcedureCode { get; set; } public sbyte Booster { get; set; } public int vaccineId { get; set; } }
DB Context代码
public DbSet<Medical_Record> Medical_Record { get; set; }
控制器代码
[HttpGet("PatientVaccines")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<IActionResult> GetPatientVaccines(long id) { var medicalRecords = await _govUkDBContext.Medical_Record.Where(x => (long)x.NHSNumber == id).ToListAsync(); if (medicalRecords == null) { return NotFound(); } return Ok(medicalRecords); }
数据库表结构

解决方案
- 核心原因:从表结构截图可见,数据库中
NHSNumber实际是int(11)类型(对应.NET的Int32),但实体类定义为long(Int64)。EF Core在解析查询时,类型不匹配触发了隐式转换逻辑,最终导致意外的Int32转String报错。 - 修正步骤:
- 同步实体类与数据库字段类型:将实体类中的
NHSNumber改为int:public int NHSNumber { get; set; } - 更新控制器参数类型:把方法参数
id也改为int,并去掉不必要的显式转换:public async Task<IActionResult> GetPatientVaccines(int id) { var medicalRecords = await _govUkDBContext.Medical_Record.Where(x => x.NHSNumber == id).ToListAsync(); if (!medicalRecords.Any()) { return NotFound(); } return Ok(medicalRecords); } - 若需存储大数值:如果
NHSNumber需要存储超出Int32范围的值,先修改数据库字段类型为bigint,再保持实体类和控制器参数的long类型一致。
- 同步实体类与数据库字段类型:将实体类中的
内容的提问来源于stack exchange,提问作者Hassan
相关产品推荐
相关产品推荐

