简体   繁体   中英

Help with LINQ to SQL query

I usually do just fine, but for some reason I cannot figure out why this particular query is defeating me.

For simplicity here is the database(Brand and PageTitle):

在此处输入图片说明

PageTitle is just a table to hold SEO data(there is only one row per Brand )

I want to : Select one row from PageTitle where brands = p (variable that holds the query string value)

This is an example of what I'm trying to do (If there are no records for the brand in PageTitle I don't want to throw an error).

var pages = da.PageTitles.Where(x => x.Brands.Single(z => z.BrandID == p)).SingleOrDefault();
                if (pages.Any())
                {
                    txtSeoTitle.Text = pages.Title;
                    txtSeoMetaKeywords.Text = pages.Keywords;
                    txtSeoMetaDesc.Text = pages.Description;
                }

Unless i'm missing something obvious, can't you just do this:

var page = db.PageTitles
              .FirstOrDefault(x => x.Brands.Any(y => y.BrandId == p));

SingleOrDefault will throw an exception if more than one row is returned, so i think you need FirstOrDefault .

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