linq查询与多对多的关系

时间:2015-08-12 16:18:38

标签: c# asp.net-mvc linq entity-framework

我一直在努力解决这个问题。我试图显示属于所选类别的所有产品。我无法弄清楚如何编写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;
    }

}

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

如果您想获得属于所选类别的所有产品,您可以尝试这一点,以防您只知道类别名称:

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

当您知道类别Id:

时,情况会更好
var category=db.Categories.Find(categoryId);
if(category!=null)
{
   var products=category.Products;
}

或者,如果您想在一行中完成所有操作,并且您确定该类别存在:

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