在EF模型使用这些类两个表涉及做组:Linq查询,通过与不直接连接
class BoxOutput
{
public long BoxId { get; set; }
public virtual Box Box { get; set; }
public long BoxId { get; set; }
public long CategoryId { get; set; }
public virtual Category Category { get; set; }
public long? ColorId { get; set; }
public virtual Category Color { get; set; }
public decimal Weight { get; set; }
// ...and other irrelevant properties
}
class BoxInput
{
public long BoxId { get; set; }
public virtual Box Box { get; set; }
public long BoxId { get; set; }
public long CategoryId { get; set; }
public virtual Category Category { get; set; }
public long? ColorId { get; set; }
public virtual Category Color { get; set; }
public decimal Weight { get; set; }
// ...and other irrelevant properties
}
......我该怎么办LINQ查询,对于一个特定的盒(如boxId = 12
),返回此?:
category.name color.name inputWeightsSum outputWeightsSum
---------------------------------------------------------------------------
c null 0 0
c red 0 0
c blue 0 0
m null 0 0
m red 0 0
m blue 0 0
....
我目前几乎实现这一目标,但“可选颜色”是给做“笛卡尔积”当我的烦恼:我没有显示空。 ..
这就是我所拥有的。
var boxesInputs = dbContext.BoxesInputs
.Where(c => c.BoxId == 12)
.GroupBy(c => new { c.CategoryId, c.ColorId })
.Select(g => new
{
categoryId = g.Key.CategoryId,
colorId = g.Key.ColorId,
sumOfWeights = g.Sum(r => (decimal?)r.Weight) ?? 0,
}).ToList();
var boxesOutputs = dbContext.BoxesOutputs
.Where(c => c.BoxId == 12)
.GroupBy(c => new { c.CategoryId, c.ColorId })
.Select(g => new
{
categoryId = g.Key.CategoryId,
colorId = g.Key.ColorId,
sumOfWeights = g.Sum(r => (decimal?)r.Weight) ?? 0,
}).ToList();
var categoriesAndColors = dbContext.Categories.AsEnumerable()
.SelectMany(category => dbContext.Colors.AsEnumerable()
.Select(color => new
{
category = new
{
categoryId = category.CategoryId,
name = category.Name,
},
color = new
{
colorId = color.ColorId,
name = color.Name,
},
inputWeightsSum = boxesInputs.Where(r => r.categoryId == category.CategoryId && r.colorId == color.ColorId).Sum(r => (decimal?) r.sumOfWeights) ?? 0,
outputWeightsSum = boxesOutputs.Where(r => r.categoryId == category.CategoryId && r.colorId == color.ColorId).Sum(r => (decimal?)r.sumOfWeights) ?? 0,
})).ToList();
在上面的代码中,前两个查询返回的:
category.name color.name inputWeightsSum
-------------------------------------------------------
c null 0
c red 0
c blue 0
m null 0
m red 0
m blue 0
....
category.name color.name outputWeightsSum
-------------------------------------------------------
c null 0
c red 0
c blue 0
m null 0
m red 0
m blue 0
....
,第三个加入这两个。我想我需要改进这个连接,因为我失去了空值。
另外,这段代码使用内存中的代码,我希望它是一个单一的sql查询(linq-to-entities而不是linq-to-objects与linq-to-entities混合)。可能吗?因为BoxOutput和BoxInput是两个不同的表格,它们不是直接相连的。不管怎样,最终我最终会得到3个查询?
我想我需要一个群组加入 – sports 2014-11-21 21:35:24
你只是想得到一个笛卡尔产品? – paqogomez 2014-11-21 21:36:50
我的代码的前两个查询被授予是正确的..我只是想将这两个合并为一个结果,按“(类别,颜色)” – sports 2014-11-21 21:44:22