我正在努力编写一个查询来填充一个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();
答案 0 :(得分:2)
如果我理解你的问题,你可以做一些简单的事情:
ProductInCategory
你可以保留查询语法,但我发现它更具可读性。
这假设Product
中的导航属性指向public Product Product { get; set; }
(未添加到问题中),定义如下:
{{1}}