我有两个表Category(Master),Products(child)。我想组合它们并获取一些数据并显示它
public partial class Product
{
public int Product_Id { get; set; }
public string Product_Name { get; set; }
public Nullable<int> Regular_Price { get; set; }
public Nullable<int> Category_Id { get; set; }
}
public partial class Category
{
public int Category_Id { get; set; }
public string Category_Name { get; set; }
}
//A viewmodel as
public class ViewModel
{
public IEnumerable<Product> Product { get; set; }
public Category Category { get; set; }
}
我的数据是
Product_Id Product_Name Price Category_Id
1 a1 5000 10
2 a2 5700 10
3 a3 5000 10
4 a4 5000 10
5 b1 1000 20
6 b2 2000 20
7 c1 4000 30
8 c2 7000 30
Category_Id Category_Name
10 A
20 B
30 C
40 D
这里我的要求是我想要像
这样的东西@foreach(var item in model
{
//Required code
}
A
a1
a2
a3
a4
B
b1
b2
C
c1
c2
ViewModel是否正确或我是否需要对其进行更改。 感谢
答案 0 :(得分:1)
根据您的输出(您显示的内容),ViewModel
应该: -
public class ViewModel
{
public IEnumerable<string> ProductName { get; set; }
public string CategoryName{ get; set; }
}
因为您对CategoryName
&amp;其各自的ProductName
,您可以像这样使用group join
: -
List<ViewModel> result = (from c in category
join p in products
on c.Category_Id equals p.Category_Id into g
select new ViewModel
{
CategoryName = c.Category_Name,
ProductName = g.Select(x => x.Product_Name)
}).ToList();
如果你想获取完整的Product
对象,那么只需改变你的ViewModel: -
public class ViewModel
{
public IEnumerable<Product> Product { get; set; }
public string CategoryName { get; set; }
}
从查询中选择完整的产品: -
//Rest of the query
select new ViewModel
{
CategoryName = c.Category_Name,
Product = g
}).ToList();
在您的视图中,您可以使用foreach
循环来显示结果,这里是完整的Working Fiddle。