1

Let's say I have a Customer table which has a PrimaryContactId field and a SecondaryContactId field. Both of these are foreign keys that reference the Contact table. For any given customer, either one or two contacts may be stored. In other words, PrimaryContactId can never be NULL, but SecondaryContactId can be NULL.

If I drop my Customer and Contact tables onto the "Linq to SQL Classes" design surface, the class builder will spot the two FK relationships from the Customer table to the Contact table, and so the generated Customer class will have a Contact field and a Contact1 field (which I can rename to PrimaryContact and SecondaryContact to avoid confusion).

Now suppose that I want to get details of all the contacts for a given set of customers.

If there was always exactly one contact then I could write something like:

from customer in customers join contact in contacts on customer.PrimaryContactId equals contact.id select ... 

...which would be translated into something like:

SELECT ... FROM Customer INNER JOIN Contact ON Customer.FirstSalesPersonId = Contact.id 

But, because I want to join on both the contact fields, I want the SQL to look something like:

SELECT ... FROM Customer INNER JOIN Contact ON Customer.FirstSalesPersonId = Contact.id OR Customer.SecondSalesPersonId = Contact.id 

How can I write a Linq expression to do that?

1
  • Isn't an INNER JOIN just a different way of writing a WHERE? Commented Mar 15, 2010 at 13:50

2 Answers 2

4

It's rarely correct to use join in LINQ to SQL.

Since you want contacts, why not start your selection there? Presuming the association between Customer and Contact is two-way, you should be able to write something like:

IEnumerable<Guid> customerIds = // ... var q = from contact in Context.Contacts where customerIds.Contains(contact.Customer.Id) select contact; 
Sign up to request clarification or add additional context in comments.

2 Comments

You could do it all in one shot too, if you want to. (+1 for link text, fully agree with you there)
@Craig: this is yet another case where in trying to simplify my question and take it out of my problem domain, I've lost some of the nuances of my situation. I don't think I can come at it the other way, no. But, I take your point about not using join at all.
1

Use anonymous classes. EG

new { A.Foo, B.Bar } equals new { Foo = B.Baz, Bar = C.Ork } 

1 Comment

Sorry, I think you've missed the point of the question. That's still an equality test - how can I do condition1 OR condition2?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.