Search code examples
c#fluent-nhibernate

How to join multible Tables using linq with fluent nHibernate (left join)?


This are my domain classes:

public class File
{
    public virtual long LFD { get; set; }

    public virtual long AK_KEY_PE_WERBER { get; set; }
    public virtual long AK_KEY_PE_RECHT { get; set; }
    
    //some other properties
}

public class Employee
{
    public virtual long LFD { get; set; }
    
    //some other properties

}

This are the mapping classes:

public class FileMap : ClassMap<File>
{
    public FileMap()
    {
        Id(x => x.LFD);
        
        Map(x => x.AK_KEY_PE_WERBER);
        
        //some other fields
    }
}

public class EmployeeMap : ClassMap<Employee>
{
    public MITARBEITERMap()
    {
        Id(x => x.LFD);
        //some other fields

    }

}

The database contains:

Files:

LFD: 1 AK_KEY_PE_WERBER: null

LFD: 2 AK_KEY_PE_WERBER: 1

Employees:

LFD: 1

So I want to create a select which gets all Files and join them with the Employee if possible.

I tried:

var contentQuery = (from file in DBSession.Query<File>()
                    join werb in DBSession.Query<Employee>()
                    on file.AK_KEY_PE_WERBER equals werb.LFD
                    select new
                    {
                        File = file,
                        Recht = werb,
                    }).ToList();
Debug.WriteLine(contentQuery.Count);

But this returns only the Files where AK_KEY_PE_WERBER is not null. So the Count is 1 instead of 2.

I tried:

var contentQuery = (from file in DBSession.Query<File>()
                    join werb in DBSession.Query<Employee>()
                    on file.AK_KEY_PE_WERBER equals werb.LFD into werbJoin
                    select new
                    {
                        File = file,
                        Recht = werbJoin.FirstOrDefault(),
                    }).ToList();

But this throws an NotImplementedException.


Solution

  • With the Help of the answer here: https://stackoverflow.com/a/23558389/9930052 this code seems to work as I wish:

            var contentQuery = (from file in DBSession.Query<File>()
                                from werb in DBSession.Query<Employee>().Where(werb => werb.LFD == file.AK_KEY_PE_WERBER).DefaultIfEmpty()
                                select new
                                {
                                    File = file,
                                    Recht = werb,
                                }).ToList();
    

    Im not exactly sure how this works but...