2012-01-31 1 views
1

タグの区切りリストを受け入れ、そのリストのすべてのタグに割り当てられた商品のリストを返すサービスメソッドがあります。LINQを使用してリスト内のすべてのタグに属する商品を返します

これは私が持っているもので、製品を返しません。私はデータを二重チェックしましたが、2つのタグに属する製品があります。

public List<Product> GetTagProducts(string tags) 
{ 
    //list of parameters 
    var tagParams = tags.Split('+').ToList(); 

    //return all products which belong to ALL tags specified in tagParams list 
    return (from pt in _repository.ProductTags 
      where tagParams.All(p => p == pt.Tag.Name) 
      select pt.Product).Distinct().Take(75).ToList(); 
} 

public class Tag 
{ 
    [Key] 
    public int TagId { get; set; } 
    public string Name { get; set; } 

    public virtual List<Product> Products { get; set; } 
    public virtual List<ProductTag> ProductTags { get; set; } 

} 

public class Product 
{ 
    public int ProductId { get; set; } 
    [Required] 
    [Display(Name = "Name")] 
    public string Name { get; set; } 
    [Required] 
    [Display(Name = "Short Description")] 
    public string ShortDescription { get; set; } 
    [Required] 
    [Display(Name = "Long Description")] 
    public string LongDescription { get; set; } 
    [Required] 
    [Display(Name = "Price")] 
    public decimal Price { get; set; } 

    public virtual List<Tag> Tags { get; set; } 
} 

public class ProductTag 
{ 
    [Key] 
    public int ProductTagId { get; set; } 
    [ForeignKey("Product")] 
    public int ProductId { get; set; } 
    [ForeignKey("Tag")] 
    public int TagId { get; set; } 

    public virtual Product Product { get; set; } 
    public virtual Tag Tag { get; set; } 
} 

//Repository 
private DatabaseContext _context = new DatabaseContext(); 
public IQueryable<ProductTag> ProductTags 
    { 
     get { return _context.ProductTags; } 
    } 



EDIT:私が探している結果を明確にします。 tagParams 2つのタグの文字列(私はこれらの両方でタグ付けされた製品を探していますという意味)を保持しているとしましょう:

Automotive 
General 

そして、我々は以下の製品を持って言うことができます:

product    tags 
-------    ---- 
Wipers    Automotive, General 
Air Freshener  General 
Gloves    General 
Tires    Automotive 
Mirror    Automotive, General 

クエリは「ワイパーを返す必要があります"と"ミラー "。

+0

右は、クラスを示すために質問を更新しました。ありがとう。 –

答えて

1

メソッドチェーンのスタイル:

List<Product> allProducts = GetAllProductsFromSomewhere(); 
allProducts.Where(p => tagParams.All(tag => 
p.Tags.Select(x => x.Name).Contains(tag))).Distinct().Take(75).ToList(); 

Allは、すべてのタグが1つのタグに等しくなければならないことを意味します。そしてあなたはそれが2つのタグを含んでいると言ったので、不可能です。
MSDNで言葉:

Determines whether all elements of a sequence satisfy a condition.

+0

gdoronありがとうございますが、彼は正しい結果を返しません。すべてのタグに属する製品を返します。すべてのタグに属する製品は返しません。私は必要な結果を明確にするために質問を編集しました。 –

+0

@ JohnL。クラスも表示してください。 '_repository.ProductTags'はどのように見えますか? – gdoron

+0

@ JohnL。私は '_repository'のように見えますが、更新された答えのようなものでなければなりません。 – gdoron

関連する問題