Skip to main content
 首页 » 编程设计

c#之具有多对多关系的linq查询

2024年02月05日17sky-heaven

我一直在为这个问题苦苦挣扎。我正在尝试显示属于所选类别的所有产品。我不知道如何编写 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));