views:

29

answers:

1

I have this contact list which I'm building using LINQ to SQL. The query to get a list of contacts is:

return db.Contacts.ToList();

In the list I also want to display each contact's primary e-mail address. To do this I first rewrite my query:

return (from db.Contacts
        select c).ToList();

I found this nice way to do left joins:

return (from db.Contacts
        from ce in ContactEmails.Where(x => x.ContactID == c.ContactID && c.IsPrimary).DefaultIfEmpty()
        select c).ToList();

But now I want to add this PrimaryEmailAddress to my Contact object. To do this I have added a property (PrimaryEmailAddress) to the generated Contact class, using a partial class.

Is it possible in the LINQ query to add the value to c.PrimaryEmailAddress somehow? My solution right now is to create anonymous objects and then iterate them.

A: 

Here's one way to do it:

  1. In your entity designer, create an association between your Contact class and your ContactEmail class (just guessing at your class names here). Here are some instructions on creating an association.

  2. Then, configure your DataContext to load only your primary ContactEmail. Here are some instructions on filtering child data at the DataContext level.

And here is an entirely different way to do it:

In your partial Contact class, in your partial OnLoaded() method, query the primary ContactEmail. For example:

partial void OnLoaded()
{
    // get your DataContext here
    this.PrimaryContactEmail = db.ContactEmails
        .Where(ce => ce.ContactID == this.ContactID && ce.IsPrimary)
        .SingleOrDefault();

}
shaunmartin