I have a question regarding foreign key in entity framework(EF4).
Lets say i have classes :
public class E1
{
public int Id{get;set;}
Public string name{get;set;}
}
public class E2
{
[ForeignKey("e1")]
public int E1Id{get;set;}
[ForeignKey("E1Id")]
public E1 e1{get;set;}
}
public class E3
{
[ForeignKey("e2")]
public int E2Id{get;set;}
[ForeignKey("E2Id")]
public E2 e2{get;set;}
}
public class E4
{
}
respectively and i suppose i want to access the attribute of class E1 in class E4 by calling via object of E3 (which internally calls E2) as well as E2 calling E1 as shown above but when i try to access the attribute of E1 it throws object null reference exception so whats the possible way to get the attributes of E1?
You need to use either eager loading, lazy loading or explicit loading to force your relation to be loaded.
Eager loading will load your relations immediately when you load the main entity:
Lazy loading will load your relations transparently on demand when you first access them (it will trigger separate database query for every accessed navigation property). To make this work all your navigation properties in every entity supporting lazy loading must be
virtual.Explicit loading demands you to manually execute loading on already loaded entity:
and you can combine it with eager loading: