简体   繁体   English

LINQ to SQL查询帮助

[英]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): 为了简单起见,这里是数据库(Brand和PageTitle):

在此处输入图片说明

PageTitle is just a table to hold SEO data(there is only one row per Brand ) PageTitle只是一个用于保存SEO数据的表(每个Brand只有一行)

I want to : Select one row from PageTitle where brands = p (variable that holds the query string value) 我想:从PageTitle中选择一行,其中brands = p(保存查询字符串值的变量)

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). 这是我要尝试做的一个示例(如果PageTitle中没有该品牌的记录,我不想抛出错误)。

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 . 如果返回多个行, SingleOrDefault将引发异常,因此我认为您需要FirstOrDefault

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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