簡體   English   中英

將數據庫植入ASP.NET Core 2.1之后,為什么數據庫仍然為空?

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

在使用實體框架的ASP.NET Core MVC Web應用程序中,我定義了以下模型:

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; }
    }
}

然后,我更新了數據庫上下文,並用測試數據為數據庫播種。 之后,我添加了遷移,將連接字符串更改為一個新字符串,然后更新了數據庫。 但是當我打開數據庫時,它是空的嗎?

注意:在將導航屬性添加到兩個模型之前,我能夠正確播種數據庫,這意味着在將以下代碼添加到Student模型之前:

            public Parent Parent { get; set; }

並將以下代碼添加到父模型:

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

它表明我正確地完成了其他部分,但是當我添加以上代碼行時,數據庫變為空。 誰能幫我找出問題所在?

有兩件事要確認:

  1. 您是否為這些導航屬性定義了關系,例如:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Parent>().HasMany(g => g.Students);

    base.OnModelCreating(modelBuilder);
}
  1. 播種時是否彼此分配了值
var parentId = 1;
var student = new Student
{
  ParentId = parentId
}
....

var parent = new Parent()
{
  ID = parentId
  Students = {student}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM