问题描述
有一个Person类和Student类,二者是继承关系。另外,Student和StudyCost是一对一关系。代码如下:[Table("Person")]publicclassPerson{[Key]publicintPersonId{get;set;}publicintAge{get;set;}publicstringName{get;set;}publicvirtualstringInfo{get;set;}publicstringDescription{get{returnInfo+Age.ToString();}set{}}}[Table("Student")]publicclassStudent:Person{publicstringCourse{get;set;}publicvirtualStudyCostStudyCost{get;set;}publicdoubleCost{get{returnStudyCost.Fee;}set{}}publicoverridestringInfo{get{returnCourse+Cost;}set{base.Info=value;}}}[Table("StudyCost")]publicclassStudyCost{[Key,ForeignKey("Student")]publicintPersonId{get;set;}publicdoubleFee{get;set;}publicvirtualStudentStudent{get;set;}}publicclassStudentDbContext:DbContext{publicStudentDbContext(stringconString):base(conString){}publicDbSet<Person>Persons{get;set;}publicDbSet<StudyCost>StudyCosts{get;set;}}
向数据库中写入对象没问题,并且表结构也符合预期:using(StudentDbContextcontext=newStudentDbContext(ConnectionString)){Personperson=newPerson{Age=16,Name="Razor",Info="Iamaordinaryguy"};Studentstudent=newStudent{Age=18,Name="Motor",Course="Math",StudyCost=newStudyCost{Fee=12000,}};context.Persons.Add(person);context.Persons.Add(student);context.SaveChanges();}
但是,单独从数据库中取回数据时:context.Configuration.LazyLoadingEnabled=true;foreach(varpersonInContextincontext.Persons){Debug.WriteLine("Age:{0,-10}tName:{1,-10}tDesp:{2}",personInContext.Age,personInContext.Name,personInContext.Description);}
总是在Student类的publicdoubleCost{get{returnStudyCost.Fee;}set{}}
属性中出现空引用异常。即使我迭代StudyCost集合并显示inclueStudent进来,仍然在上述位置出现同样异常。请问问题在哪里?
解决方案
本帖最后由 htcfan 于 2015-11-05 17:20:47 编辑