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

ASP.NET Core 5 MVC种子数据类型转换异常:无法将String转为Int32

ASP.NET Core 5 待办清单种子数据 InvalidCastException 问题解决

问题描述

使用ASP.NET Core 5开发待办清单应用时,集成种子数据遇到以下错误:

InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'

推测问题出在priority变量上——将该字段类型改为string并调整种子数据后,应用可正常运行。相关代码如下:

模型类(To_Do.cs)

using Microsoft.AspNetCore.Components.Forms;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace To_Do_List.Models
{
    public class To_Do
    {
        public int Id { get; set; }

        [StringLength(60, MinimumLength=3)]
        [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Title must begin with a capital letter and be a minimum 3 characters long with a maximum of 60 characters.")]
        [Required]
        public string? Title { get; set; }

        [StringLength(60, MinimumLength = 3)]
        [Required]
        public string? Description { get; set; }

        [Required]
        [Display(Name = "Start Date")]
        [DataType(DataType.Date)]
        public DateTime StartDate { get; set; }

        [Required]
        [Display(Name = "End Date")]
        [DataType(DataType.Date)]
        public DateTime EndDate { get; set; }

        [Display(Name = "Priority")]
        public int priority { get; set; }

        [Display(Name = "Completed?")]
        public bool checkbox { get; set; }
    }
}

SeedData.cs 文件

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using To_Do_List.Data;
using System;
using System.Linq;
using To_Do_List.Models;

namespace To_Do_List.Models;

public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new To_Do_ListContext(
            serviceProvider.GetRequiredService<
                DbContextOptions<To_Do_ListContext>>()))
        {
            if (context.To_Do.Any())
            {
                return;   // DB已完成种子数据初始化
            }

            context.To_Do.AddRange(
                new To_Do
                {
                    Title = "test",
                    Description = "this is a test",
                    StartDate = DateTime.Parse("2023-4-22"),
                    EndDate = DateTime.Parse("2023-4-28"),
                    checkbox = true,
                    priority = 3
                }
            );
            context.SaveChanges();
        }
    }
}

问题原因与解决方案

核心原因

数据库中priority字段的类型为字符串(如nvarchar/varchar),但模型类中定义为int类型,EF Core读取数据时尝试将字符串转换为整数,触发类型转换异常。

解决步骤

  1. 核对数据库字段类型
    直接查看数据库内To_Do表的priority字段类型,若为字符串,需修改为整数类型(如int/tinyint)。

  2. 通过EF Core迁移同步模型与数据库
    若采用Code First模式,确保模型类的priority为int类型(当前代码已符合),执行以下命令更新数据库:

    Add-Migration FixPriorityDataType
    Update-Database
    

    该操作会自动调整数据库字段类型,使其与模型匹配。

  3. 清理或转换旧数据(可选)
    若数据库中已有字符串类型的priority数据,需先清空表或手动将数据转换为整数(如把"3"改为3),否则执行迁移时可能报错。

  4. 检查上下文配置
    打开To_Do_ListContext.cs,确认OnModelCreating方法中是否存在强制将priority配置为字符串的代码,例如:

    modelBuilder.Entity<To_Do>().Property(t => t.priority).HasColumnType("nvarchar(50)");
    

    若存在,删除该配置,让EF Core自动根据模型类型生成对应字段。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 18:43:13