1

I have an application where I have a model composed of several other objects. For instance:

class Customer
{
  public int CustomerId{get;set;}
  public int? AddressId {get;set;} // this is set as allow null in database
  public string Name {get;set}
  public virtual Addresss Address {get;set;}
}

class Address
{
 public int AddressId {get;set}
 public string A1 {get;set}
}

The idea is to use context.customers.include("Address"). However the model I am currently working on is much more complex than the above.

I have used https://stackoverflow.com/a/51772067 as a reference, but unfortunately this does not work for an id having no value (nullable, as the database allows nulls)

How can I modified the expression to behave as a true left join (includes an empty entity if the id is null).

Thanks in advance for your assistance

djgrech
  • 26
  • 1

1 Answers1

0

As per the official doc you could do left join as below

List<Person> people = new List<Person> { magnus, terry, charlotte, arlene };
    List<Pet> pets = new List<Pet> { barley, boots, whiskers, bluemoon, daisy };

    var query = from person in people
                join pet in pets on person equals pet.Owner into gj
                from subpet in gj.DefaultIfEmpty()
                select new { person.FirstName, PetName = subpet?.Name ?? String.Empty };

When you use DefaultIfEmpty() then it becomes a left join. Upvote if it works.

Ajinkya Gadgil
  • 117
  • 1
  • 8
  • Thanks for the reply. I have tried to use the a similar linq statement to the above, but the thing is that the application shows a list of columns for the entire entity object (and other objects within the class, such as Address.A1), and the user can select which columns will be queried. The idea is to generate a select statement with minimum required fields and the statement will be executed at the server side. So basically the columns can be selected dynamically. Thanks – djgrech Jan 21 '21 at 11:59