1

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?

1
  • 4
    try to set your navigation property virtual as public virtual List<HistoryEntry> Entries { get; set; } Commented Oct 23, 2014 at 9:40

2 Answers 2

4

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; } 
Sign up to request clarification or add additional context in comments.

Comments

2

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:

http://www.dotnet-tricks.com/Tutorial/entityframework/RIWW210913-Difference-between-Lazy-Loading-and-Eager-Loading.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.