简体   繁体   中英

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;

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM