请帮忙看下Entity Framework中 Navigation property 的问题。
有一个 Person
类和 Student
类,二者是继承关系。
另外,Student
和 StudyCost
是一对一关系。
代码如下:
[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
进来,仍然在上述位置出现同样异常。
请问问题在哪里?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论