I have a Sheet that can contain many Sections. Each Section can also contain many Sections. I would like to load the Sheet, its Sections, and all of the sub Sections with as few round trips to the database as possible. Practically, I think this will usually be 1-2 levels deep, but it may go up to 16. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
public class Sheet {
public long Id { get; set; }
// more fields
public virtual IList<Section> Sections { get; set; }
}
public class Section {
public long Id { get; set; }
public long SheetId { get; set; }
[ForeignKey("SheetId")]
public virtual Sheet Sheet { get; set; }
public long? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Section Parent { get; set; }
public virtual IList<Section> Sections { get; set; }
// more fields
}
public class MyDbContext : DbContext {
public DbSet<Sheet> Sheets { get; set; }
public DbSet<Section> Sections { get; set; }
public Sheet GetSheetConfiguration(long id) {
Configuration.LazyLoadingEnabled = false;
Sheet rtn;
rtn = Sheets.Find(id);
(Sections.Where(sect => sect.SheetId == id)).ToList();
return rtn;
}
}
This creates the desired table structure: Sheets: Id (pk), ... Sections: Id (pk), SheetId (not null), ParentId (null)
The GetSheetConfiguration method loads all of the Sections related to that sheet and lets EF sort it out. It gets the relationships correct except that all of the Sections are also in Sheet.Sections. (I wanted to have SheetId set for every Section to avoid recursive queries.) How do I tell EF to only use Sections where ParentId = null at the Sheet level? - List item
GetSheetConfigurationcorrect? I don't understand the line(Sections.Where ... )Sections.Where(sect => sect.SheetId == id).Load();