Search code examples
c#model-view-controllerentity

Why my database is still empty after I seed it in ASP.NET Core 2.1?


In an ASP.NET Core MVC web app using Entity Framework, I defined my models as follows:

using System.Linq;
using System.Threading.Tasks;

namespace NewTechParentPortalV3.Models
{
    public class Student
    {
        public int StudentID { get; set; }
        [StringLength(50, ErrorMessage = "Last name cannot be longer than 50 
characters.")]
        public string LastName { get; set; }
        [StringLength(50, ErrorMessage = "First name cannot be longer than 
50 characters.")]
        public string FirstMidName { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", 
ApplyFormatInEditMode = true)]
        public DateTime EnrollmentDate { get; set; }
        public int ParentID { get; set; }

        public ICollection<Enrollment> Enrollments { get; set; }
        public Parent Parent { get; set; }
    }

    public class Parent
    {
        public int ID { get; set; }
        [StringLength(50, ErrorMessage = "Last name cannot be longer than 50 
characters.")]
        public string LastName { get; set; }
        [StringLength(50, ErrorMessage = "First name cannot be longer than 
50 characters.")]
        public string FirstMidName { get; set; }
        public string Address { get; set; }
        public string Telephone { get; set; }
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

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

Then I updated the database context, and seeded the database with test data. After that, I added migrations, changed the connection string to make a new one and then updated the database. But when I open the database, it is empty?

Note: I was able to seed database correctly before I add navigation properties to both models, I mean before adding the following codes to Student model:

            public Parent Parent { get; set; }

and adding the following codes to Parent model:

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

It shows that I did the other parts correctly, but when I add the above lines of code, the database becomes empty. Can anyone help me find out the problem?


Solution

  • Two things to confirm :

    1. Have you defined the relationships for those navigational properties, like:
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Parent>().HasMany(g => g.Students);
    
        base.OnModelCreating(modelBuilder);
    }
    
    1. Have you assigned values to each other when seeding
    var parentId = 1;
    var student = new Student
    {
      ParentId = parentId
    }
    ....
    
    var parent = new Parent()
    {
      ID = parentId
      Students = {student}
    }