在MVC中创建视图会导致错误

时间:2014-03-23 09:20:51

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

我有一个这样的学生班:

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中使用创建视图创建学生模型时,我收到此错误:

  

一个或多个实体的验证失败。请参阅&#39; EntityValidationErrors&#39;物业详情。

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

我的学生控制器创建模型:

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

我使用EF6创建此模型,

1 个答案:

答案 0 :(得分:1)

  

参见&#39; EntityValidationErrors&#39;物业详情。

尝试查看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.