Reputation: 9305
I have the following Entity classes:
public class History : BaseEntity
{
public string Version { get; set; }
public DateTime? ReleaseDate { get; set; }
public string Name { get; set; }
public string Additional { get; set; }
public List<HistoryEntry> Entries { get; set; }
}
public class HistoryEntry : BaseEntity
{
public string Version { get; set; }
public string BugNr { get; set; }
public AllowedTypes EntryType { get; set; }
public string Description { get; set; }
public History Parent { get; set; }
}
public enum AllowedTypes
{
Bug, Enhancement
}
which are mapped that way:
public HistoryMap()
{
ToTable("History");
HasKey(c => c.Version);
Property(c => c.Version).HasMaxLength(10);
Property(c => c.Name).HasMaxLength(200);
}
this results in two tables that act exactly like I wanted ("History" has "Version" as primary key and "HistoryEntry" has a foreign Key "Version" that is linked to "History"."Version"
After Adding some stuff into these tables I try to read the contents:
IQueryable<History> query = _historyRepository.Table.OrderByDescending(c => c.ReleaseDate);
var historyList = new List<Core.Domain.Tengo.History>(query);
While all History-Entries are read successfully, the "Entries"-Property if the "History"-Object is always NULL.
How do I achieve that the linked Items are also read and stored into Entries?
Upvotes: 1
Views: 115
Reputation: 174
Yves answer is correct if you want to use Lazy Loading.
The other way to do this is to use Eager Loading. Eager loading loads the properties immediately rather than when it is accessed. The snippet below uses Eager Loading.
_historyRepository.Table.Include(x=>x.Entries).OrderByDescending(c => c.ReleaseDate);
The difference between Lazy and eager loading are explained in the link below:
Upvotes: 2
Reputation: 3473
Navigation properties such as ICollection<T>
/ IList<T>
should be marked as virtual
. This allows EntityFramework to override them and provide code for lazy-loading the properties.
So the line (in the History
class)
public List<HistoryEntry> Entries { get; set; }
Should become
public virtual List<HistoryEntry> Entries { get; set; }
Upvotes: 4