Reputation:
I have an app with Entity Framework 5 code-first this is sample of my classes:
public partial class PlaningCourseAssistant
{
public PlaningCourseAssistant() {}
public int ID { get; set; }
public int PlaningCourseID { get; set; }
public int AssistantID { get; set; }
public virtual PlaningCourse PlaningCourse { get; set; }
public virtual Teacher Assistant { get; set; }
}
And
public class Teacher
{
public Teacher()
{
...
this.PlaningCourseAssistants = new HashSet<PlaningCourseAssistant>();
}
public int ID { get; set; }
public string Name{ get; set; }
....
public virtual ICollection<PlaningCourseAssistant> PlaningCourseAssistants { get; set; }
}
And
public partial class PlaningCourse
{
public PlaningCourse()
{
...
this.PlaningCourseAssistants = new HashSet<PlaningCourseAssistant>();
}
public int ID { get; set; }
public string Title { get; set; }
...
public virtual ICollection<PlaningCourseAssistant> PlaningCourseAssistants { get; set; }
}
when i add a new object to my PlaningCourseAssistant
like this :
var pcb = new PlaningCourseAssistant
{
PlaningCourseID = CourseID,
AssistantID = assistantID,
};
try
{
planingCourseAssistantService.Add(pcb);
uow.SaveChanges();
} catch { }
afterward when i want to get PlaningCourseAssistant
list, the added PlaningCourseAssistant
's Assistant
navigation key is null.
Why this happen? And how can I fix this?
Upvotes: 1
Views: 294
Reputation: 32447
EF can not lazy load the 'Assistant' property because the PlaningCourseAssistant
instance you are using is not a proxy created by EF.
You can either use explicit loading
context.Entry(pcb).Reference(p => p.Assistant).Load();
context.Entry(pcb.Assistant).Collection(p => p.PlaningCourseAssistant).Load();
Or let EF create a proxy instance of PlaningCourseAssistant
var pcb = context.PlaningCourseAssistants.Create();
Upvotes: 2