我有两个模型,分类和子类别,一对多的关系。
然后我有一个名为Notice的模型,它与Subcategory有一对一的关系(SubcategoryId为FK)。
用户添加了他们想要监控的子类别。 当子类别中发生某些事情时,他们会被注意到。
现在我正在尝试打印出信息,以便用户可以了解正在监视哪些子类,如下所示:
(icon) Category Y
Subcategory - monitored
Subcategory - monitored
Subcategory - not monitored
(icon) Category X
Subcategory - not monitored
Subcategory - monitored
Subcategory - not monitored
目前我通过以下方式解决了这个问题:
var SubcatsAndCheckedNotices =
from subcat in db.Subcategories
join notice in db.Notices.Where(x=>x.CompanyId == company.CompanyId) on subcat.SubcategoryId equals notice.SubcategoryId into prodGroup
from item in prodGroup.DefaultIfEmpty()
select new CheckedNoticesViewModel() {CategoryId =subcat.CategoryId, Category = subcat.Category, Subcategory = subcat, Checked = (item.SubcategoryId == null ? false : true) };
哪个几乎有效,问题是我需要按照上面的说明将其打印出来,因此需要进行不同的选择(对于类别)并且通过这样做我将失去对其他类别属性的访问权限,例如我需要的Icon属性。
我被困住了,知道有更好的方法可以做到这一点,但我无法弄明白。
以下是我的模型:
public class Category
{
public int CategoryId { get; set; }
public string Icon { get; set; }
public string Title { get; set; }
public ICollection<Subcategory> Subcategories { get; set; }
}
public class Subcategory
{
public int SubcategoryId { get; set; }
public string Title { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class Notice
{
public int NoticeId { get; set; }
public int SubcategoryId { get; set; }
public virtual Subcategory Subcategory { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
有什么建议吗?
答案 0 :(得分:0)
我认为你在寻找的是
var Results = db.Notices.Where(x => x.CompanyId == company.CompanyId)
.Select(x => new CheckedNoticesViewModel()
{
CategoryId = x.Subcategory.CategoryId,
Category = x.Subcategory.Category,
Subcategory = x.Subcategory,
Checked = x.SubcategoryId = null ? false : true
}
.GroupBy(y => y.CategoryId);
foreach(var Result in Results)
{
Print(Result.Key.(Information you want to print));
foreach(var CheckedNoticesViewModel in Result)
{
Print(CheckedNoticesViewModel.(Information you want to print);
}
}
编辑:不是这样的:
foreach(var Category in db.Categories)
{
Print(Category.Title);
foreach (var SubCategoryNotice in Category.Subcategories.GroupJoin(db.Notices, x => x.SubcategoryId, y => y.SubcategoryId, (x, y) => new { SubCategory= x, Notice =y }))
{
Print(SubCategoryNotice.SubCategory.Title + " " + (SubCategoryNotice.Notice.Any(x => x.CompanyId == 1) ? true: false));
}
}
答案 1 :(得分:0)
我采取了另一种方法来解决它。
获取已检查子类别的一个查询,将其与类别一起发送到视图。 打印出类别和子类别,并检查checkNotices中是否存在子类别。而不是试图加入一切。
ViewBag.Categories = db.Categories.ToList();
var checkedNotices =
from subcategory in db.Subcategories
join notice in db.Notices.Where(x => x.CompanyId == company.CompanyId) on subcategory.SubcategoryId
equals notice.SubcategoryId
select
new CheckedNoticesViewModel()
{
CategoryId = subcategory.CategoryId,
SubcategoryId = subcategory.SubcategoryId,
};
return View(checkedNotices.ToList());