I have a Profile class that has a father property which self references to itself, I want to load a profile together with its fathers profile in one sql join statement
Select * FROM profile left join profile as father on profile.fatherid = father.id where profile.id = 650
So i created the following linq statement, but instead of running the sql statement about it runs the following statements
select * from profiles
select * from profiles where id = 650
Then in memory it groups them together, but obviously i would not want to load the whole database.
private class Result
{
public Profile Profile { get; set; }
public IEnumerable<Profile> Fathers { get; set; }
}
private Result MapFather(Profile p, IEnumerable<Profile> father)
{
return new Result() {Profile = p, Fathers = father.DefaultIfEmpty()};
}
var profiles = from p in db.Profiles where p.ID.Equals(650) select p;
var fathers = from f in db.Profiles select f;
var groupJoin = profiles.GroupJoin(fathers,
p => p.FatherID,
f => f.ID,
MapFather).ToList();
Your call to GroupJoin() is getting the IEnumerable version because of your call to MapFather is a Func<,> instead of Expression>. Therefore the calls to profiles and fathers are being executed before the GroupJoin.
Try inlining MapFather():