首页 > 请帮忙看下Entity Framework中 Navigation property 的问题。

请帮忙看下Entity Framework中 Navigation property 的问题。

有一个 Person 类和 Student 类,二者是继承关系。
另外,StudentStudyCost一对一关系。
代码如下:

    [Table("Person")]
    public class Person
    {
        [Key]
        public int PersonId { get; set; }

        public int Age { get; set; }

        public string Name { get; set; }

        public virtual string Info { get; set; }

        public string Description
        {
            get
            {
                return Info + Age.ToString();
            }
            set
            {
            }
        }
    }

    [Table("Student")]
    public class Student : Person
    {
        public string Course { get; set; }

        public virtual StudyCost StudyCost { get; set; }

        public double Cost {
            get
            {
                return StudyCost.Fee;
            }
            set
            {
            }
        }

        public override string Info
        {
            get
            {
                return Course + Cost;
            }
            set { base.Info = value; }
        }
    }

    [Table("StudyCost")]
    public class  StudyCost
    {
        [Key, ForeignKey("Student")]
        public int PersonId { get; set; }

        public double Fee { get; set; }
        public virtual Student Student { get; set; }
    }
 public class StudentDbContext : DbContext
    {
        public StudentDbContext(string conString ):base(conString)
        {
            
        }
        public DbSet<Person> Persons { get; set; }
        public DbSet<StudyCost> StudyCosts { get; set; }
     }

向数据库中写入对象没问题,并且表结构也符合预期:

using (StudentDbContext context = new StudentDbContext(ConnectionString))
        {
            Person person = new Person
            {
                Age = 16,
                Name = "Razor",
                Info = "I am a ordinary guy"

            };

            Student student = new Student
            {
                Age = 18,
                Name = "Motor",
                Course = "Math",
                StudyCost = new StudyCost
                {
                    Fee = 12000,
                }

            };

            context.Persons.Add(person);
            context.Persons.Add(student);
            context.SaveChanges();

}

但是,单独从数据库中取回数据时:

 context.Configuration.LazyLoadingEnabled = true;
foreach (var personInContext in context.Persons)
            {
                Debug.WriteLine("Age:{0,-10}\tName:{1,-10}\tDesp:{2}", personInContext.Age, personInContext.Name, personInContext.Description);
            }

总是在 Student类的

  public double Cost {
        get
        {
            return StudyCost.Fee;
        }
        set
        {
        }
    }
    

属性中出现空引用异常。
即使我迭代StudyCost集合并显示inclue Student进来,仍然在上述位置出现同样异常。

请问问题在哪里?

【热门文章】
【热门文章】