タグの区切りリストを受け入れ、そのリストのすべてのタグに割り当てられた商品のリストを返すサービスメソッドがあります。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
クエリは「ワイパーを返す必要があります"と"ミラー "。
右は、クラスを示すために質問を更新しました。ありがとう。 –