I would like to do a LINQ query that returns all of the records for the Parent table, and includes the Child, if applicable. I know I can do a LINQ join with DefaultIfEmpty()
, but then I must output a ViewModel. I'd like to get an IQuerable<Parent>
of the actual Parent Class.
So, if I have these classes:
public class Parent
{
[Key]
public int ParentId {get; set;}
public string ParentName {get; set;}
public int? MyChildId {get; set;}
[ForeignKey("MyChildId")]
public virtual Child MyChild {get; set;}
public bool IsActive {get;set;}
}
public class Child
{
public int ChildId {get;set;}
public string ChildName {get;set;}
}
In LINQPad, if I do this:
var results = db.Parent.Where(ra => ra.IsActive);
results.Dump();
I get 111 records.
If I do this:
var results = db.Parent.Where(ra => ra.IsActive);
var results2 = (from r in results
select new
{
ParentId = r.ParentId,
ParentName = r.ParentName,
MyChildId = r.MyChildId
});
results2.Dump();
I also receive 111 records.
But if I do this:
var results = db.Parent.Where(ra => ra.IsActive);
var results2 = (from r in results
select new
{
ParentId = r.ParentId,
ParentName = r.ParentName,
MyChildId = r.MyChildId,
IsActive = r.IsActive,
MyChildName = r.MyChild == null ? null : r.MyChild.ChildName
});
results2.Dump();
I only get 50 records. These are the 50 Parent
records that have a child. If they do not have a child, they don't come back.
The SQL generated looks like this:
SELECT
[Extent1].[ParentId] AS [ParentId],
[Extent1].[ParentName] AS [ParentName],
[Extent1].[IsActive] AS [IsActive],
[Extent2].[ChildName] AS [ChildName]
FROM [dbo].[Parent] AS [Extent1]
INNER JOIN [dbo].[Child] AS [Extent2] ON [Extent1].[MyChildId] = [Extent2].[ChildId]
WHERE [Extent1].[IsActive] = 1
How can I get a resultset that includes all 111 Parent
records, even if they have no child, but does include the Child
elements, if they are there?
UPDATE So, I may have lied a bit. I posted the above for simplicity sake, but just in case it helps, here is a closer sample of what the code does:
public class Parent
{
[Key]
public int ParentId {get; set;}
public string ParentName {get; set;}
public int? MyChildId {get; set;}
[ForeignKey("MyChildId")]
public virtual Child MyChild {get; set;}
[ForeignKey("MyChildId")]
public virtual StepChild MyStepChild {get; set;}
public bool IsActive {get;set;}
}
public class Child
{
public int ChildId {get;set;}
public string ChildName {get;set;}
}
public class StepChild
{
public int StepChildId {get;set;}
public string StepChildName {get;set;}
}