我在下表中有一对多关系
产品 [ProductId,Name(varchar)]
关键字 [KeywordId,关键字(varchar)]
KeywordsToProducts [Id,ProductId,KeywordId]
假设搜索文本是“blue pro”。我需要使用operator'和'搜索这两个关键字。 如果我执行以下操作:
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)))
然后我没有任何说法,因为字段关键字只包含一个单词。
我如何加入'Keywrods.Keyword'db字段记录以便使用'and'运算符进行搜索?
答案 0 :(得分:0)
如果您将每个匹配的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;