views:

95

answers:

2

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  A: 

Use anonymous classes. EG

new { A.Foo, B.Bar } equals new { Foo = B.Baz, Bar = C.Ork }
leppie
Sorry, I think you've missed the point of the question. That's still an equality test - how can I do condition1 OR condition2?
Gary McGill
See my comment.
leppie
+2  A: 

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;
Craig Stuntz
You could do it all in one shot too, if you want to. (+1 for link text, fully agree with you there)
leppie
@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.
Gary McGill