I'm writing an application that will allow our users to send newsletters to their contacts. Here is the database structure (only important fields):
Contacts(tbl) ContactEmails(tbl) Newsletters(tbl)
ContactID ContactEmailID NewsletterID
... ContactID (fk) ...
EmailAddress
Deleted
...
NewsletterLists(tbl) NewsletterToLists(tbl)
NewsletterListID NewsletterID (fk)
... NewsletterListID (fk)
NewsletterListToContacts(tbl)
NewsletterListID (fk)
ContactID (fk)
Active
Deleted
UnsubscribedOn
...
Now I have a class structured as:
public class NewsletterContactEmails
{
public int ContactID { get; set; }
public List<string> EmailList { get; set; }
}
I want to have a NewsletterContactEmails object for each contact so that I can loop through it and send one email each contact (not each email address).
I have the Newsletter object to start working with. So in pseudo it would be...
1. Get NewsletterLists this newsletter is to send to.
2. Get Active (double opted-in) and non-deleted/unsubscribed DISTINCT Contact List from said NewsletterLists.
3. Create NewsletterContactEmails object for each contact and add their non-deleted DISTINCT list of email addresses.
I want to do this in one query. Here is what I currently have, I think I'm close but this won't even compile:
List<NewsletterContactEmails> Recipients = objNewsletter.NewsletterToLists
.Select(ntl => ntl.NewsletterList.NewsletterListToContacts
.Where(nl => nl.Active == true && nl.Deleted == false && nl.UnsubscribedOn == null)
.Select(nl => new NewsletterContactEmails {
ContactID = nl.ContactID,
EmailList = nl.Contact.ContactEmails.Where(ce => ce.Deleted == false).Select(ce => ce.EmailAddress).Distinct().ToList()
}));
Any help is greatly appreciated!
List<NewsletterContactEmails> Recipients = objNewsletter.NewsletterToLists
.SelectMany(ntl => ntl.NewsletterList.NewsletterListToContacts
.Where(nl => nl.Active == true && nl.Deleted == false && nl.UnsubscribedOn == null)
.Select(nl => new NewsletterContactEmails
{
ContactID = nl.ContactID,
EmailList =
nl.Contact.ContactEmails.Where(ce => ce.Deleted == false)
.Select(ce => ce.EmailAddress)
.Distinct()
.ToList()
}));
Try the first select as SelectMany
instead of Select
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.