I have two tables and one is self-referencing like this:
Job (id, description)
JobAssembly (id, jobid, parentassemblyid)
I have two domain objects in similar fashion:
public class Job
{
public int Id { get; set; }
public string Description { get; set; }
public virtual List<JobAssembly> Assemblies { get; set; }
}
public class JobAssembly
{
public int Id { get; set; }
public int JobId { get; set; }
public virtual Job { get; set; }
public int? ParentAssemblyId { get; set; }
public virtual JobAssembly ParentAssembly { get; set; }
public virtual List<JobAssembly> SubAssemblies { get; set; }
}
Here is the problem. When I use EF:
using (var db = new JobContext())
{
var job = db.Jobs.Find(1);
}
I get, as expected, the job requested. But it comes with ALL of the assemblies - not just the parents but the sub assemblies. Again this is expected.
My question is: How do I instruct EF to only bring in JobAssemblies which have no subassemblies... as the default behavior? I know how to query EF for said parent assemblies. But is there a way to set the mappings, or some other way, to set the default query behavior to only get the assemblies whose parentassemblyid == null?
Thanks :)
EDIT:
Allow me to illustrate:
I have a Job with id = 1. It has one Assembly with id = 1. Assembly 1 has two sub assemblies with ids = 2 and 3 respectively. When var job = db.Jobs.Find(1) is executed, EF populates the object graph like so:
The job has all three assemblies (because jobid on all three == 1). JobAssembly with id 1 has its subassemblies populated appropriately.
All of this is expected, but it would be nice if I could customize how EF is loading the objects. Job should not have every JobAssembly where JobId == 1, but only where JobId == 1 and ParentAssemblyId == null.