通过实体框架MVC

时间:2016-05-28 14:46:44

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

我想将学生表中的学生数据及其地址保存在学生详细信息表格中,我无法在第二个表格中插入数据。

错误是对象引用未设置为对象的实例。

学生模特

public partial class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Nullable<System.DateTime> CreatedDate { get; set; }
}

StudentDetails

public partial class StudentDetail
{
    public int Id { get; set; }
    public string Address { get; set; }
    public Nullable<System.DateTime> CreatedDate { get; set; }
}

查看模型

public class StudentViewModel
{
    public Student Students { get; set; }

    public StudentDetail StudentDetails { get; set; }

}

DbSet

public partial class SampleEntities : DbContext
{
    public SampleEntities()
        : base("name=SampleEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }


    public System.Data.Entity.DbSet<Basics.Models.Student> Students { get; set; }

    public System.Data.Entity.DbSet<Basics.Models.StudentDetail> StudentDetails { get; set; }
}

控制器

private SampleEntities db = new SampleEntities();

动作

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentViewModel model)
{
    if (ModelState.IsValid)
    {
        model.Students.CreatedDate = DateTime.Now;
        db.Students.Add(model.Students);
        db.SaveChanges();
        //The Newly created Id gets created and when saving that Id in anothr table the exception comes  
        model.StudentDetails.Id = model.Students.Id;
        //For Time Being in real time it won't be hard coded  
        model.StudentDetails.Address = "New Jersey";
        db.StudentDetails.Add(model.StudentDetails);
        db.SaveChanges(); 
        return RedirectToAction("Index");
    }

    return View(model.Students);
}

1 个答案:

答案 0 :(得分:0)

为什么没有

public StudentDetail StudentDetails { get; set; }

在学生班级中,并更改

的ID
public int StudentId { get; set; } 

然后在StudentDetail中更改Id

public int StudentId { get; set; } 

就像Entity Framework能够以1比1的关系加入他们一样。您必须根据需要添加一些主键/外键。