简体   繁体   English

与多对多关系的linq查询

[英]linq query with many to many relationship

I have been struggling with this one for a while. 我已经为此挣扎了一段时间。 I am trying to show all products that belong to the selected category. 我正在尝试显示属于所选类别的所有产品。 I can't figure out how to write the linq query. 我不知道如何编写linq查询。 I have a Product model and a Category model. 我有一个产品模型和一个类别模型。 Each product can belong to several categories and obviously each category can have several products. 每个产品可以属于多个类别,显然每个类别可以具有多个产品。 I will show my Product context, Product model and Category model below. 我将在下面显示我的产品上下文,产品模型和类别模型。

Product context 产品环境

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; }
}

Product model 产品型号

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;
    }

}

Category model 类别模型

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));

If you want to get all products that belong to the selected category, you can try this in case you only know the category name: 如果要获取属于所选类别的所有产品,可以尝试这种操作,以防仅知道类别名称:

var category=db.Categories.FirstOrDefault(c=>c.categoryDBName==category);
if(category!=null)
{
   var products=category.Products;
}

It's even better when you know the category Id: 当您知道类别ID时,效果会更好:

var category=db.Categories.Find(categoryId);
if(category!=null)
{
   var products=category.Products;
}

Or in case you want to do it all in one line and you're sure that the category exist: 或者,如果您想全部完成一行操作,并且确定该类别存在,请执行以下操作:

var products=db.Categories.First(c=>c.Id==categoryId).Products;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM