我在下面的表中一个一对多的关系
产品的[ProductID,名称(VARCHAR)
关键字 [KeywordId,关键词(VARCHAR)]
KeywordsToProducts [ID,产品编号,KeywordId]
比方说,搜索文本是“蓝亲”。 我需要寻找使用运营商“和”两个关键字。 如果我做到以下几点:
string test="blue pro";
string[]words = test.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var query = from p in Products
join kp in KeywordsToProducts on p.ProductId equals kp.ProductId
join kw in Keywords on kp.KeywordId equals kw.KeywordId
where (words.All(x=>kw.Keyword.Contains(x)))
然后,因为现场的关键字只包含一个字,我不GEET什么。
我如何加入“Keywrods.Keyword”数据库字段的记录,以便使用“和”运算符来搜索?
如果你加入的每个匹配KeywordsToProducts
到Keywords
,你可以收集起来并进行比较:
var query = from p in Products
join kp in KeywordsToProducts on p.ProductId equals kp.ProductId into kpj
let kws = (from kp in kpj join kw in Keywords on kp.KeywordId equals kw.KeywordId select kw.Keyword)
where words.All(w => kws.Any(kw => kw.Contains(w)))
select p;
但是,我认为这是比较容易理解(也可能是更有效),如果你做的KeywordsToProducts
到Keywords
join
分别与第一(注意,它显示了连接表会更好名为KeywordIdsToProductIds
):
var kwToProducts = from kp in KeywordsToProducts
join kw in Keywords on kp.KeywordId equals kw.KeywordId
select new { kp.ProductId, kw.Keyword };
var query = from p in Products
join kwp in kwToProducts on p.ProductId equals kwp.ProductId into kwpj
where words.All(w => kwpj.Any(kwp => kwp.Keyword.Contains(w)))
select p;
虽然我不是(一定)提它的粉丝,也注意到EF导航属性可以隐藏连接表,使这个查询更容易为好。
这将是这样的:
var query = from p in Products
where words.All(w => p.Keywords.Any(k => k.Contains(w)))
select p;
我假设你的意思是使用String.Contains
这样用户就可以在键入关键词的部分,仍然找到匹配。 如果你想要求所有的关键字进行匹配,这里是相同的代码:
var query = from p in Products
join kp in KeywordsToProducts on p.ProductId equals kp.ProductId into kpj
let kws = (from kp in kpj join kw in Keywords on kp.KeywordId equals kw.KeywordId select kw.Keyword)
where words.All(w => kws.Contains(w))
select p;
拆分增补:
var kwToProducts = from kp in KeywordsToProducts
join kw in Keywords on kp.KeywordId equals kw.KeywordId
select new { kp.ProductId, kw.Keyword };
var query = from p in Products
join kwp in kwToProducts on p.ProductId equals kwp.ProductId into kwpj
where words.All(w => kwpj.Select(kwp => kwp.Keyword).Contains(w))
select p;
EF导航属性:
var query = from p in Products
where words.All(w => p.Keywords.Contains(w))
select p;