我已经为此挣扎了一段时间。我正在尝试显示属于所选类别的所有产品。我不知道如何编写linq查询。我有一个产品模型和一个类别模型。每个产品可以属于多个类别,显然每个类别可以具有多个产品。我将在下面显示我的产品上下文,产品模型和类别模型。

产品环境

public class ProductContext : DbContext
{

    public ProductContext()
        : base("DefaultConnection")
    {
        Database.SetInitializer<ProductContext>(new CreateDatabaseIfNotExists<ProductContext>());
    }

    public DbSet<CategoryModel> Categories { get; set; }
    public DbSet<ProductModel> Products { get; set; }
    public DbSet<BrochureModel> Brochures { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        //modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        //modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        modelBuilder.Entity<CategoryModel>().ToTable("Categories");
        modelBuilder.Entity<ProductModel>().ToTable("Products");
        modelBuilder.Entity<BrochureModel>().ToTable("Brochures");

        modelBuilder.Entity<ProductModel>()
        .HasMany(p => p.ProductCategories)
        .WithMany(p => p.Products)
        .Map(m =>
        {
            m.ToTable("ProductCategory");
            m.MapLeftKey("ProductID");
            m.MapRightKey("CategoryID");
        });

    }

    public System.Data.Entity.DbSet<newBestPlay.Models.RegisterViewModel> RegisterViewModels { get; set; }
}


产品型号

public class ProductModel
{

    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Index("ItemNumber", 1, IsUnique = true)]
    [Display(Name = "Item #")]
    public int itemNumber { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Product")]
    [MaxLength(50)]
    public String product { get; set; }

    [Display(Name = "Description")]
    [MaxLength(500)]
    public String description { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool active { get; set; }

    [Display(Name = "Image Name")]
    public String imageName { get; set; }

    [Display(Name = "PDF Name")]
    public String PDFName { get; set; }

    [Display(Name = "Category(s)")]
    public virtual ICollection<CategoryModel> ProductCategories { get; set; }

    public int[] SelectedCategories { get; set; }

    public IEnumerable<SelectListItem> CategorySelectList { get; set; }

    //public ICollection<CategoryModel> CategoryList { get; set; }

    public virtual BrochureModel Brochure { get; set; }

    public IEnumerable<SelectListItem> BrochureList { get; set; }

    [Display(Name = "Category(s)")]
    public String CategoryList { get; set; }

    public static IEnumerable<SelectListItem> getCategories(int id = 0)
    {
        using (var db = new ProductContext())
        {
            List<SelectListItem> list = new List<SelectListItem>();
            var categories = db.Categories.ToList();
            foreach (var cat in categories)
            {
                SelectListItem sli = new SelectListItem { Value = cat.ID.ToString(), Text = cat.categoryName };

                //if (id > 0 && cat.ID == id)
                //{
                //    sli.Selected = true;
                //}
                list.Add(sli);
            }
            return list;
        }

    }

    public ProductModel()
    {
        active = true;
    }

}


类别模型

public class CategoryModel
{

    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Category Name")]
    [MaxLength(50)]
    public String categoryName { get; set; }

    [MaxLength(50)]
    public String categoryDBName { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool isActive { get; set; }

    //public virtual ICollection<ProductCategory> ProductCategories { get; set; }

    public virtual ICollection<ProductModel> Products { get; set; }

    public String getFullCategoryName(string category)
    {
        String fullCategoryName = "category";
        using (var db = new ProductContext())
        {
            if (!String.IsNullOrEmpty(category))
            {
                var result = from c in db.Categories
                             where c.categoryDBName.Equals(category)
                             select c.categoryName;
                fullCategoryName = result.FirstOrDefault().ToString();
            }
        }
        return fullCategoryName;
    }

}

最佳答案

您需要这样的内容,其中categoryName是您选择的类别名称:

var products = db.Products.Where(p=>p.ProductCategories.Any(c=>c.categoryName == categoryName));

10-06 00:40