1
私は、いくつかの単一のプロパティとオブジェクトのリストで構成されるビューモデルを作成するためのクエリを作成するのに苦労しています。単一のプロパティとオブジェクトのリストで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 products = _context.ProductCategories
.Select(category => new ViewModelProductCategory
{
Id = category.Id,
ParentId = category.ParentId,
Title = category.Title,
SortOrder = category.SortOrder,
NumOfProducts = category.ProductInCategory.Count()
Products = category.ProductInCategory
.Select(pic => new ViewModelProduct
{
Id = pic.Product.Id,
Title = pic.Product.Title,
Price = pic.Product.Price,
Info = pic.Product.Info
}
.ToList();
}).ToList();