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?
Two things to confirm :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasMany(g => g.Students);
base.OnModelCreating(modelBuilder);
}
var parentId = 1;
var student = new Student
{
ParentId = parentId
}
....
var parent = new Parent()
{
ID = parentId
Students = {student}
}