实体框架4.1两个跟踪查询



我正在学习EF,所以如果这个问题在其他地方得到了回答,我深表歉意。我找不到解决办法。我正在使用两个跟踪查询,因为我不能使用包括,因为它不支持条件。所以我的代码如下:

    List<int> CategoryIDs = _categoryIDs.Split(',').Select(t => int.Parse(t)).ToList();

My models:

 public class Genre
{
    public int GenreID { get; set; }
    public string Name  { get; set; }
    public string iconURL{ get; set; }
    public string Description { get; set; }
    public int DisplaySequence { get; set; }
    public IList<Category> Categories { get; set; 
}

   public class Category
   {

    public int CategoryId { get; set; }
    public int GenreID { get; set; }
    public string CategoryName { get; set; }
    public virtual Genre Genre { get; set; }
   }

     public class SubCategory
      {

    public int SubCategoryID { get; set; }     
    public int CategoryID { get; set; }
    public string SubCategoryName { get; set; }  
    public virtual Category Category { get; set; } 
}

然后是我的视图模型:

public class HomeIndexData
{
    public IEnumerable<Genre> Genres { get; set; }
    public IEnumerable<Category> Categories { get; set; }
    public IEnumerable<SubCategory> SubCategories { get; set; }         
}

然后我试图返回视图模型到我的索引:

     public ActionResult Index()
     {
     var genres = db.Genres.ToList().OrderBy(g => g.DisplaySequence);
     var categories = db.Categories.Include(i => i.SubCategories)
                     .Where(i => CategoryIDs.Contains(i.CategoryId));
            foreach (var category in categories)
            {
            };
           HomeIndexData viewModel = new HomeIndexData
            {
                Genres = genres                         
            };
            return View(viewModel);      
        }

它返回结果,但我也想过滤子类别。我如何把WHERE条件而不是。include (I => I . subcategories)。

请注意,我不想返回匿名类型,这就是为什么我是两个跟踪查询。

提前感谢。

好了,我想我知道你想做什么了:

// so filter out categories
var categories = db.Categories.Where(c => CategoryIDs.Contains(c.CategoryID)); 
// so filter out subcategories - I'm not sure what kind of filtering you want on subcategories
var subcategories = db.Subcategories.Where(s => CategoryIDs.Contains(s.SubCategoryID)); 
// so alternatively just do this: var subcategories = db.Subcategories.Where(s => s.DoYourFilteringForSubcategories);
foreach (var subcategory in subcategories)
    var cat = categories.SingleOrDefault(c => c.CategoryID == subcategory.CategoryID)
    if (cat != null)
    {
        cat.Subcategories.Add(subcategory);
    }
    else
    {
        // very good question? what are you going to do with subcategories that
        //match your criteria, but its category does not meet category filter
    }

在你的模型中你需要添加:

   public class Category
   {
    public int CategoryId { get; set; }
    public int GenreID { get; set; }
    public string CategoryName { get; set; }
    public virtual Genre Genre { get; set; }
    **public virutal List<Subcategory> Subcategories{ get; set; }**
   }

那么你最终只得到与过滤器匹配的类别,并且只包含与过滤器匹配的子类别。

最新更新