在MVC中创建视图导致错误

本文关键字:错误 视图 创建 MVC | 更新日期: 2023-09-27 17:52:17

我有一个这样的学生班级:

namespace DomainClasses
{
    using System;
    using System.Collections.Generic;
    public partial class Student
    {
        public Student()
        {
            this.Scores = new HashSet<Score>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public string IntNo { get; set; }
        public string FatherName { get; set; }
        public string BirthLocation { get; set; }
        public string Birthday { get; set; }
        public string ImageUrl { get; set; }
        public string Major { get; set; }
        public string Degree { get; set; }
        public string IdentNo { get; set; }
        public string Address { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public System.DateTime RegisterDate { get; set; }
        public string StudentId { get; set; }
        public string State { get; set; }
        public virtual ICollection<Score> Scores { get; set; }
    }
}

这个类有一个存储库类来处理请求:

public  class StudentRepository
{
        readonly EducationDBEntities _dbcontext = new EducationDBEntities();
        public void AddNewStudent(Student student)
        {
            _dbcontext.Students.Add(student);
        }
        public void RemoveStudent(Student student)
        {
            _dbcontext.Students.Remove(student);
        }
        public List<Student> GetStudentlist()
        {
            return _dbcontext.Students.ToList();
        }
        public Student FindStudentById(int id)
        {
            return _dbcontext.Students.Find(id);
        }
        public void Update(Student student)
        {
            _dbcontext.Entry(student).State = EntityState.Modified;
        }
        public void Save()
        {
            _dbcontext.SaveChanges();
        }
}

当我尝试在MVC中使用创建视图创建学生模型时,我得到了这个错误:

一个或多个实体的验证失败。详细信息请参见'EntityValidationErrors'属性。

所以这个异常来自存储库类的Save方法。我的意思是,当我想保存上下文时,我得到了这个错误。

创建模型的学生控制器:

[HttpPost]
public ActionResult Create(Student student)
{
     obj.AddNewStudent(student);
     obj.Save();
     return RedirectToAction("Index", "Student");
}

我使用EF6创建这个模型,

在MVC中创建视图导致错误

详情请参阅'EntityValidationErrors'属性。

尝试查看EntityValidationErrors属性以获取更多详细信息。用

替换_dbcontext.SaveChanges();
try
{
    _dbcontext.SaveChanges();
}
catch (DbEntityValidationException validationException)
{
     // Just use the debugger to inspect validationException
     // here, or output EntityValidationErrors in some way.
}    // <== You can set a breakpoint here.