ADO.NET Entity framework navigation property trap.
Navigation properties (EntityCollection or EntityReference) of entity object can be automatically loaded without calling their Load method because of they can be already loaded to ObjectStateManager before.
Such behaviour may confuse people how are newbie in using EF
and they started use these properties without calling load
method before. (You can also use include method of your
entity set)
As written in msdn your should first of check if EntityCollection or EntityReference is loaded then if not call the load method.
Also to simplify this process i write some extensions methods which incapsulate this logic:
namespace
System.Data.Objects.DataClasses
{
/// <summary>
///
Entity extensions
/// </summary>
public
static
class
EntityExtensions
{
/// <summary>
///
Ensures that entity referenced by <paramref name="entityReference"/>
is loaded.
/// </summary>
public
static
void
EnsureLoad<TEntity>(this
EntityReference<TEntity> entityReference)
where TEntity :
EntityObject
{
if
(!entityReference.IsLoaded)
{
entityReference.Load();
}
}
/// <summary>
///
Ensures that entity collection is loaded.
/// </summary>
public
static
void
EnsureLoad<TEntity>(this
EntityCollection<TEntity> entityCollection)
where TEntity :
EntityObject
{
if
(!entityCollection.IsLoaded)
{
entityCollection.Load();
}
}
}
}