接合体表を経由してその製品を数える私は道オフかもしれないが、いくつかのグーグルは、このクエリを生成するために私をリードしてきました:C#のクエリのカテゴリと
VMCategory = from pc in _context.ProductCategories
join pic in _context.ProductsInCategories
on pc.Id equals pic.ProductCategoryId
group pic by pc into x
select new ViewModelProductCategory
{
Id = x.Key.Id,
ParentId = x.Key.ParentId,
Title = x.Key.Title,
SortOrder = x.Key.SortOrder,
NumOfProductsInThisCategory = x.Count(c => [SOMETHING IS MISSING])
}).
ToList();
私はカテゴリでのviewmodelリストを移入しようとしていますエンティティモデルの項目、および各カテゴリのすべての製品の数です。
私は(カテゴリオブジェクトのリスト内の項目など)の結果、このタイプのものが必要です
Id = 6 (from ProductCategory)
ParentId = 4 (from ProductCategory)
Title = "Example" (from ProductCategory)
SortOrder = 2 (from ProductCategory)
NumOfProductsInThisCategory = 7 (count products from ProductsInCategories)
は、これらは私のモデルです:
のViewModel:
public class ViewModelProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public int NumOfProductsInThisCategory { get; set; }
}
エンティティモデル:
public class ProductCategory
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
}
public class ProductInCategory
{
public int Id { get; set; }
public int ProductId { get; set; }
public int ProductCategoryId { get; set; }
public int SortOrder { get; set; }
}
[GROUPBYカウントとLINQ](HTTPSの可能性のある重複:// stackoverflowの.com/questions/7285714/linq-with-groupby-and-count) –
'x.Count()'のままにした場合どうなりますか? [Fiddle](https://dotnetfiddle.net/#)を作れますか? –