Search code examples
c#wpfentity-framework-6code-firstsql-server-2016-express

Insert data to database with FK relation


I use code-first to generate the database and data at runtime.

My two classes/models have one-to-many relationship. As a FK cannot be null I first insert a Standard before inserting a Student, and I also manually type in the FK ID as well. Yet I still get System.NullReferenceException and I just cannot understand why?

I tried googling but I cannot find related article on inserting data with foreign relation from scratch in code-first.

My Entity Class/Model

public class Student {
    public Student() { }
    public int StudentID { get; set; }
    public string StudentName { get; set; }

    public int StandardId { get; set; } // FK StandardId
    public Standard Standard { get; set; } }

public class Standard {
    public Standard() { }
    public int StandardId { get; set; }
    public string StandardName { get; set; } 

    public ICollection<Student> Students { get; set; } }

My Main

using (MyDbContext ctx = new MyDbContext())
{
    Standard std = new Standard();
    ctx.Standards.Add(std);
    ctx.SaveChanges(); // Database already has a StandardID = 1

    Student stud = new Student()
    {
        StudentName = "John",
        StandardId = 1  // I even manually type in the FK
    };

    ctx.Student.Add(stud); // I still get 'System.NullReferenceException'
    ctx.SaveChanges();
}

Solution

  • Don't manually add your StandardId, do this:

    using (MyDbContext ctx = new MyDbContext())
    {
        Standard std = new Standard();
    
        Student stud = new Student()
        {
            StudentName = "John",
        };
    
        stud.Standard = std;
    
        ctx.Student.Add(stud);
        ctx.SaveChanges();
    }
    

    EF will take care of the relation.