如何根据条件显示来自两个主子 table 的数据

How to display data from two master and child table based upon a condition

我有两个表 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 是否正确,或者我是否需要对其进行更改。 谢谢

根据你的输出(你所展示的)你的 ViewModel 应该是:-

public class ViewModel
    {
        public IEnumerable<string> ProductName { get; set; }
        public string CategoryName{ get; set; }
    }

既然您对 CategoryName 及其各自的 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; }
    }

和select查询的完整产品:-

//Rest of the query
select new ViewModel
        {
             CategoryName = c.Category_Name,
             Product = g
        }).ToList();

在您的视图中,您可以使用 foreach 循环来显示结果,这里是完整的 Working Fiddle