Justen
Justen

Reputation: 4869

Need help populating an asp:dropdownlist from multiple tables in an SQL database

I have 4 tables: CustomerDocument, CustomerLink, CustomerAdditionalInfo, and CustomerImage. They each have a value of CustomerNumber, and I need to way to pull the customer numbers from each table and put in a drop down list. I know how to do it with one table, but not multiple. Also, there is a restriction that the CustomerNumber needs to be not null, so do I need to include this with each join? Here is a bit of code I have now. oDb is the DataContext

var oData = from c in oDb.CustomerAdditionalInfos
                    where ( c.CustomerID == CustomerID && 
                            c.CustomerNumber != null   && 
                            c.CategoryID == CategoryID )

                    orderby c.CustomerNumber
                    select new { c.CustomerNumber };

        return oData;

Upvotes: 0

Views: 1275

Answers (1)

Ryan Alford
Ryan Alford

Reputation: 7594

You could do this....

var oData = (from c in oDb.CustomerAdditionalInfos
             where c.CustomerNumber != null
             select new 
             {
                  CustomerNumber = c.CustomerNumber
             }).Union
                 (from d in oDb.CustomerDocument
                  where d.CustomerNumber != null
                  select new
                  {
                      CustomerNumber = d.CustomerNumber
                  }).Union
                      (from l in oDb.CustomerLink
                       where l.CustomerNumber != null
                       select new
                       {
                           CustomerNumber = l.CustomerNumber
                       }).Union
                            (from i in oDb.CustomerImage
                             where i.CustomerNumber != null
                             select new
                             {
                                 CustomerNumber = i.CustomerNumber
                             }).OrderBy(c => c.CustomerNumber);

That is simply a union of all of the CustomerNumbers in all four tables. This WILL include duplicates if there are duplicates. If you want only distinct CustomerNumbers, then just do a Distinct() after the OrderBy.

Upvotes: 2

Related Questions