查询使用单个属性和对象列表填充viewmodel对象

时间:2017-12-20 16:48:19

标签: c# entity-framework-core

我正在努力编写一个查询来填充一个viewmodel,它包含一些属性和一个对象列表。

这些是我的实体模型:

public class ProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public List<ProductInCategory> ProductInCategory { get; set; }
}

public class ProductInCategory
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int SortOrder { get; set; }
    public int ProductCategoryId { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Info { get; set; }
    public decimal Price { get; set; }
}

这是我的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 NumOfProducts { get; set; }
    public List<ViewModelProduct> Products { get; set; }
}

这是我在查询之前填充viewmodel到视图之前的距离:

var VMCategory = (from Category in _context.ProductCategories
  join ProdInCat in _context.ProductsInCategories
  on Category.Id equals ProdInCat.ProductCategoryId
  join Product in _context.Products
  on ProdInCat.ProductId equals Product.Id
  select new ViewModelProductCategory
  {
      Id = Category.Id,
      ParentId = Category.ParentId,
      Title = Category.Title,
      SortOrder = Category.SortOrder,
      NumOfProducts = ... // Perhaps count something?
      Products = ... // A list of products
  }).ToList();

此图片说明了我期望查询结果如何: Expected result

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你可以做一些简单的事情:

ProductInCategory

你可以保留查询语法,但我发现它更具可读性。

这假设Product中的导航属性指向public Product Product { get; set; } (未添加到问题中),定义如下:

{{1}}