【问题标题】:Contoso University Project: InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'Contoso 大学项目:InvalidCastException:无法将“System.String”类型的对象转换为“System.Int32”类型
【发布时间】:2020-09-30 17:51:35
【问题描述】:

我正在 .net 核心中处理 Contoso 大学项目,当我从导航菜单中选择“学生”以查看学生列表时,然后在每个学生姓名下方的页面上选择“详细信息”链接学生,我收到以下错误:

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

它说错误出现在 StudentsController.cs 的这一行:

+
37            var student = await _context.Students

任何关于问题可能是什么的建议都会非常有帮助。

这是我的控制器代码:

//StudentController.cs

// GET: Students/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .Include(s => s.Enrollments)
                    .ThenInclude(e => e.Course)
                .AsNoTracking()
                .FirstOrDefaultAsync(m => m.ID == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

// SchoolContext.cs

    namespace ContosoUniversity.Data
    {
        public class SchoolContext : DbContext
        {
            public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
            {
            }
    
            public DbSet<Course> Courses { get; set; }
            public DbSet<Enrollment> Enrollments { get; set; }
            public DbSet<Student> Students { get; set; }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Course>().ToTable("Course");
                modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
                modelBuilder.Entity<Student>().ToTable("Student");
            }
        }
    }

// Student.cs(模型)

    namespace ContosoUniversity.Models
    {
        public class Student
        {
            public int ID { get; set; }
            public string LastName { get; set; }
            public string FirstMidName { get; set; }
            public DateTime EnrollmentDate { get; set; }
            public ICollection<Enrollment> Enrollments { get; set; }
        }
    }

// Index.cshtml(列表视图)

    @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstMidName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.EnrollmentDate)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
                </td>
            </tr>
    }

// Enrollment.cs

    namespace ContosoUniversity.Models
    {
   }
        public class Enrollment
        {
            public int EnrollmentID { get; set; }
    
            public int CourseID { get; set; }
    
            public int StudentID { get; set; } // foreign key
    
    // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
            public string Grade { get; set; } // nullable
    // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
    
            public Course Course { get; set; } // foreign key
    
            public Student Student { get; set; }
    
        }
    }

我的数据结构:

dbo.Course:
CourseId (PK, int, not null)
Title (varchar(255), not null)
Credits (int, null)

dbo.Enrollment
EnrollmentId (PK, int, not null)
StudentID( int, null)
CourseID (int, null)
Grade (varchar(255), null)

Student
Id(PK, int, not null)
FirstMidName(varchar(255), null)
LastName(varchar(255), null)
EnrollmentDate(datetime, null)

【问题讨论】:

  • 这可能是无关的,但我已经编辑了问题以删除最后的名称签名。你有礼貌很好,但这并不是真正需要的:)如果有人在这个社区上发布答案,相信我,他们已经决定这样做,出于他们自己的原因。

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

看看这一行:

var student = await _context.Students
         .Include(s => s.Enrollments)
         .ThenInclude(e => e.Course)
         .AsNoTracking()
         .FirstOrDefaultAsync(m => m.ID == id);

你传入一个可为空的 int 吗?

public async Task<IActionResult> Details(int? id)

在类中它只是 int

   public int ID { get; set; }

尝试将 nullable (int?) 转换回 (int) like

 var student = await _context.Students
            .Include(s => s.Enrollments)
            .ThenInclude(e => e.Course)
            .AsNoTracking()
            .FirstOrDefaultAsync(m => m.ID == (int)id);

【讨论】:

  • 感谢您的建议 - 我已经尝试过了,但仍然无法正常工作。它提到了一个字符串,所以我不确定这与它有什么关系。
  • 尝试去掉 .include 和 .theninclude (只是为了缩小范围)....但是请记住这一点...接下来会出错。
  • 将您的注册模型放入 OP...它有课程吗?
  • @RobertYoung...见上面的注释
  • 嗨@Chris 是的,注册模型确实有课程。我已经尝试注释掉'.ThenInclude'并且错误仍然存​​在。我已经尝试注释掉“.Include”和“.ThenInclude” - 错误消失了,但我得到一个不同的说法,说现在没有注册(如预期的那样)。
猜你喜欢
  • 2019-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 2013-11-04
  • 2021-10-25
相关资源
最近更新 更多