asp.net - Lazy loading not working in Entity Framework -
i have 2 classes connected using virtual keyword:
student:
public class student { public int studentid{get; set;} public string lastname { get; set; } public string firstname { get; set; } public datetime enrollmentdate { get; set; } public virtual ienumerable<enrollment> enrollments { get; set; } }
enrollment:
public class enrollment { public int enrollmentid { get; set; } public int courseid { get; set; } public int studentid { get; set; } public decimal? grade { get; set; } public virtual course course { get; set; } public virtual student student { get; set; } }
both tables populated, , have corresponding records (for instance, there student id 1 , enrollments student id 1).
i'm pulling student it's id , sending view
student student = db.students.find(id); return view(student);
in view can display details student. @model
contain enrollment
property (at least comes in intellisense , doesn't red-line), null
.
there course class:
{ public int courseid { get; set; } public string coursename { get; set; } public int totalcredits { get; set; } }
since @model.enrollments
null
, can't access @model.enrollment.coursenamae
.
edit: tried hack workaround:
ienumerable<student> temp = db.students.include(s => s.enrollments); student student = temp.firstordefault(s => s.studentid.equals(id)); return view(student);
this giving me error on second line:
system.invalidoperationexception: specified include path not valid. entitytype 'myfirstproject2.models.student' not declare navigation property name 'enrollments'.
does offer clues?
a little bit late here explanation between lazy loading vs eager loading
and rules lazy loading:
- context.configuration.proxycreationenabled should true.
- context.configuration.lazyloadingenabled should true.
- navigation property should defined public, virtual. context not lazy loading if property not define virtual.
edit: 1 last thing relationships use:
public virtual icollection<enrollment> enrollments { get; set; }
other links:
Comments
Post a Comment