这些位于下表中。我无法修改它
Brand
Id Name IsRegisterd
1 ABC True
2 XYZ True
产品
Id Name BrandId Active Version
1 Soap ABC True 1.0
2 Soap ABC True 2.0
3 Oil Xyz True
我需要像品牌名称、产品名称和版本列表这样的输出。 以下是我的查询。但无法获取版本列表。如何做到这一点。
from b in DbContext.Brand
join p in oneAssetContext.Products on Brand.Id equals p.BrandId into PslJ
from Ptagged in PslJ.Where(p => (P.Active == true)).DefaultIfEmpty()
where IsRegisterd = true
select new SinglePoductDetails
{
BrandName = Brand.Name,
Product = Product.Name,
Version =
}
我需要像品牌名称、产品名称和版本列表这样的输出。下边是 我的查询。但无法获取版本列表。如何做到这一点。
根据您共享的代码片段,我尝试重现您的场景并发现了几个问题。
首先,在您的查询中,上下文和变量名称不是使用属性。具体来说,变量
Brand
和 Product
尚未以正确的方式标记。
另一个主要错误是,在 join 子句中错误地使用了 DefaultIfEmpty 方法。您尝试以不适合左连接上下文的方式使用它。
最明显的流程是,您没有按照应有的方式使用 group by 子句。
解决方案:
为了根据您的场景和描述获取和显示数据,您应该以适当的方式使用 GroupBy 和 SelectMany,以便它将获取每个品牌的产品版本列表。
您需要做的就是按品牌和产品名称对数据进行分组,然后 选择所需的字段,包括版本列表。
让我们看看如何在实践中实现这一目标:
演示模型:
public class Brand
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsRegistered { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int BrandId { get; set; }
public bool Active { get; set; }
public string Version { get; set; }
}
public class SingleProductDetails
{
public string BrandName { get; set; }
public string ProductName { get; set; }
public List<string> Versions { get; set; }
}
注意:我根据您的共享查询制作了上述课程,请随意根据您的实际代码调整表格。
控制器:
public IActionResult Index()
{
var brands = new List<Brand>
{
new Brand { Id = 1, Name = "ABC", IsRegistered = true },
new Brand { Id = 2, Name = "XYZ", IsRegistered = true }
};
var products = new List<Product>
{
new Product { Id = 1, Name = "Soap", BrandId = 1, Active = true, Version = "1.0" },
new Product { Id = 2, Name = "Soap", BrandId = 1, Active = true, Version = "2.0" },
new Product { Id = 3, Name = "Oil", BrandId = 2, Active = true, Version = "1.0" },
new Product { Id = 4, Name = "Oil", BrandId = 2, Active = true, Version = "1.1" },
new Product { Id = 5, Name = "Oil", BrandId = 2, Active = false, Version = "2.0" }
};
var result = from b in brands
join p in products on b.Id equals p.BrandId
where b.IsRegistered == true && p.Active == true
group p by new { BrandName = b.Name, ProductName = p.Name } into g
select new SingleProductDetails
{
BrandName = g.Key.BrandName,
ProductName = g.Key.ProductName,
Versions = g.Select(x => x.Version).ToList()
};
var productDetailsList = result.ToList();
return View(productDetailsList);
}
查看:
@model List<SingleProductDetails>
<h2>Product Details</h2>
<table class="table">
<thead>
<tr>
<th>Brand Name</th>
<th>Product Name</th>
<th>Versions</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.BrandName</td>
<td>@item.ProductName</td>
<td>@string.Join(", ", item.Versions)</td>
</tr>
}
</tbody>
</table>
输出:
注意:有关group by和group join
的详细信息请参考此官方文档