Left Outer Join LINQ To Entities
I have the following entities:
Clients
-- ClientID -- ClientNameContractor
-- ContractorID -- ContractorNamePreferredContractors
-- PreferredContractorID -- ClientID -- ContractorIDSo I have a list of clients and contractors. The clients prefer to work with certain contractors than the others. I want to build 开发者_如何学Ca 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?
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
};
精彩评论