Kumar
Kumar

Reputation: 2863

Left Outer Join LINQ To Entities

I have the following entities:

Clients
-- ClientID
-- ClientName

Contractor
-- ContractorID
-- ContractorName

PreferredContractors
-- PreferredContractorID
-- ClientID
-- ContractorID

So I have a list of clients and contractors. The clients prefer to work with certain contractors than the others. I want to build a LINQ to Entity query which pulls all the contractors with a boolean field indicating whether the contractor is preferred or not.

 public IQueryable<PreferredContractor> GetPreferredContractors(int clientID)
    {
        var preferredContractors = from c in db.Contractors
                  from pc in db.PreferredContractors.DefaultIfEmpty()
                  select new PreferredContractor
                             {
                                 ContractorID = c.ContractorID,
                                 ContractorName = c.ContractorName,
                                 IsPreferred = // This is where I need help
                             };

        return preferredContractors;
    }

How can I determine if the contractor is preferred or not?

Upvotes: 0

Views: 921

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292755

    var preferredContractors =
              from c in db.Contractors
              join pc in db.PreferredContractors.Where(pc2 => pc2.ClientId == clientId) on c.ContractorId equals pc.ContractorId into j
              from pc in j.DefaultIfEmpty()
              select new PreferredContractor
                         {
                             ContractorID = c.ContractorID,
                             ContractorName = c.ContractorName,
                             IsPreferred = pc != null
                         };

Upvotes: 3

Related Questions